_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
2292b6b2545c8e5a68b7404a2736429d24fa33bcd9eded931964365846d58b3d
rizo/snowflake-os
e1000.mli
val init : unit -> unit
null
https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/kernel/e1000.mli
ocaml
val init : unit -> unit
3b29aeaaf11aa9971594c8db2fdc4f3b734e702639f5f342b251ec832dd987cd
parapluu/Concuerror
concuerror_ticket_tests.erl
%%%---------------------------------------------------------------------- Copyright ( c ) 2011 , < > , < > and < > . %%% All rights reserved. %%% This file is distributed under the Simplified BSD License . %%% Details can be found in the LICENSE file. %%%---------------------------------------------------------------------- Author : < > < > %%% Description : Ticket interface unit tests %%%---------------------------------------------------------------------- -module(concuerror_ticket_tests). -include_lib("eunit/include/eunit.hrl"). Spec for auto - generated test/0 function ( eunit ) . -spec test() -> 'ok' | {'error', term()}. -spec get_error_test() -> 'ok'. get_error_test() -> Error = concuerror_error:mock(), Pid = spawn(fun() -> ok end), concuerror_lid:start(), Lid = concuerror_lid:new(Pid, noparent), Actions = [{'after', Lid}, {'block', Lid}], Ticket = concuerror_ticket:new(Error, Actions), concuerror_lid:stop(), ?assertEqual(Error, concuerror_ticket:get_error(Ticket)). -spec get_details_test() -> 'ok'. get_details_test() -> Error = concuerror_error:mock(), Pid = spawn(fun() -> ok end), concuerror_lid:start(), Lid = concuerror_lid:new(Pid, noparent), Actions = [{'after', Lid}, {'block', Lid}], Ticket = concuerror_ticket:new(Error, Actions), concuerror_lid:stop(), ?assertEqual(Actions, concuerror_ticket:get_details(Ticket)).
null
https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/resources/utest/concuerror_ticket_tests.erl
erlang
---------------------------------------------------------------------- All rights reserved. Details can be found in the LICENSE file. ---------------------------------------------------------------------- Description : Ticket interface unit tests ----------------------------------------------------------------------
Copyright ( c ) 2011 , < > , < > and < > . This file is distributed under the Simplified BSD License . Author : < > < > -module(concuerror_ticket_tests). -include_lib("eunit/include/eunit.hrl"). Spec for auto - generated test/0 function ( eunit ) . -spec test() -> 'ok' | {'error', term()}. -spec get_error_test() -> 'ok'. get_error_test() -> Error = concuerror_error:mock(), Pid = spawn(fun() -> ok end), concuerror_lid:start(), Lid = concuerror_lid:new(Pid, noparent), Actions = [{'after', Lid}, {'block', Lid}], Ticket = concuerror_ticket:new(Error, Actions), concuerror_lid:stop(), ?assertEqual(Error, concuerror_ticket:get_error(Ticket)). -spec get_details_test() -> 'ok'. get_details_test() -> Error = concuerror_error:mock(), Pid = spawn(fun() -> ok end), concuerror_lid:start(), Lid = concuerror_lid:new(Pid, noparent), Actions = [{'after', Lid}, {'block', Lid}], Ticket = concuerror_ticket:new(Error, Actions), concuerror_lid:stop(), ?assertEqual(Actions, concuerror_ticket:get_details(Ticket)).
e5012b88b88f9f6566c87b4f4958ed7362be2e0e26232178dddce26d0f8a47ef
facebook/pyre-check
taintAnalysis.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. *) (* TaintAnalysis: this is the entry point of the taint analysis. *) open Core open Pyre open Taint module Target = Interprocedural.Target let initialize_configuration ~static_analysis_configuration: { Configuration.StaticAnalysis.configuration = { taint_model_paths; _ }; rule_filter; source_filter; sink_filter; transform_filter; find_missing_flows; dump_model_query_results; maximum_model_source_tree_width; maximum_model_sink_tree_width; maximum_model_tito_tree_width; maximum_tree_depth_after_widening; maximum_return_access_path_width; maximum_return_access_path_depth_after_widening; maximum_tito_collapse_depth; maximum_tito_positions; maximum_overrides_to_analyze; maximum_trace_length; maximum_tito_depth; _; } = Log.info "Verifying model syntax and configuration."; let timer = Timer.start () in let taint_configuration = let open Core.Result in TaintConfiguration.from_taint_model_paths taint_model_paths >>= TaintConfiguration.with_command_line_options ~rule_filter ~source_filter ~sink_filter ~transform_filter ~find_missing_flows ~dump_model_query_results_path:dump_model_query_results ~maximum_model_source_tree_width ~maximum_model_sink_tree_width ~maximum_model_tito_tree_width ~maximum_tree_depth_after_widening ~maximum_return_access_path_width ~maximum_return_access_path_depth_after_widening ~maximum_tito_collapse_depth ~maximum_tito_positions ~maximum_overrides_to_analyze ~maximum_trace_length ~maximum_tito_depth |> TaintConfiguration.exception_on_error in let taint_configuration_shared_memory = TaintConfiguration.SharedMemory.from_heap taint_configuration in (* In order to save time, sanity check models before starting the analysis. *) let () = ModelParser.get_model_sources ~paths:taint_model_paths |> List.iter ~f:(fun (path, source) -> ModelParser.verify_model_syntax ~path ~source) in let () = Statistics.performance ~name:"Verified model syntax and configuration" ~phase_name:"Verifying model syntax and configuration" ~timer () in taint_configuration, taint_configuration_shared_memory let parse_and_save_decorators_to_skip ~inline_decorators { Configuration.Analysis.taint_model_paths; _ } = Analysis.InlineDecorator.set_should_inline_decorators inline_decorators; if inline_decorators then ( let timer = Timer.start () in Log.info "Getting decorators to skip when inlining..."; let model_sources = ModelParser.get_model_sources ~paths:taint_model_paths in let decorators_to_skip = List.concat_map model_sources ~f:(fun (path, source) -> Analysis.InlineDecorator.decorators_to_skip ~path source) in List.iter decorators_to_skip ~f:(fun decorator -> Analysis.InlineDecorator.DecoratorsToSkip.add decorator decorator); Statistics.performance ~name:"Getting decorators to skip when inlining" ~phase_name:"Getting decorators to skip when inlining" ~timer ()) (** Perform a full type check and build a type environment. *) let type_check ~scheduler ~configuration ~cache = Cache.type_environment cache (fun () -> Log.info "Starting type checking..."; let configuration = (* In order to get an accurate call graph and type information, we need to ensure that we schedule a type check for external files. *) { configuration with Configuration.Analysis.analyze_external_sources = true } in let errors_environment = Analysis.EnvironmentControls.create ~populate_call_graph:false configuration |> Analysis.ErrorsEnvironment.create in let type_environment = Analysis.ErrorsEnvironment.type_environment errors_environment in let () = Analysis.ErrorsEnvironment.project_qualifiers errors_environment |> Analysis.TypeEnvironment.populate_for_modules ~scheduler type_environment in type_environment) let parse_models_and_queries_from_sources ~taint_configuration ~scheduler ~resolution ~source_sink_filter ~callables ~stubs sources = TODO(T117715045 ): Do not pass all and stubs explicitly to map_reduce , * since this will marshal - ed between processes and hence is costly . * since this will marshal-ed between processes and hence is costly. *) let map state sources = let taint_configuration = TaintConfiguration.SharedMemory.get taint_configuration in List.fold sources ~init:state ~f:(fun state (path, source) -> ModelParser.parse ~resolution ~path ~source ~taint_configuration ~source_sink_filter:(Some source_sink_filter) ~callables ~stubs () |> ModelParseResult.join state) in Scheduler.map_reduce scheduler ~policy: (Scheduler.Policy.fixed_chunk_count ~minimum_chunks_per_worker:1 ~minimum_chunk_size:1 ~preferred_chunks_per_worker:1 ()) ~initial:ModelParseResult.empty ~map ~reduce:ModelParseResult.join ~inputs:sources () let parse_models_and_queries_from_configuration ~scheduler ~static_analysis_configuration: { Configuration.StaticAnalysis.verify_models; configuration = { taint_model_paths; _ }; _ } ~taint_configuration ~resolution ~source_sink_filter ~callables ~stubs = let ({ ModelParseResult.errors; _ } as parse_result) = ModelParser.get_model_sources ~paths:taint_model_paths |> parse_models_and_queries_from_sources ~taint_configuration ~scheduler ~resolution ~source_sink_filter ~callables ~stubs in let () = ModelVerificationError.verify_models_and_dsl errors verify_models in parse_result let initialize_models ~scheduler ~static_analysis_configuration ~taint_configuration ~taint_configuration_shared_memory ~class_hierarchy_graph ~environment ~initial_callables = let open TaintConfiguration.Heap in let resolution = Analysis.TypeEnvironment.ReadOnly.global_resolution environment in Log.info "Parsing taint models..."; let timer = Timer.start () in let callables_hashset = initial_callables |> Interprocedural.FetchCallables.get_non_stub_callables |> Target.HashSet.of_list in let stubs_hashset = initial_callables |> Interprocedural.FetchCallables.get_stubs |> Target.HashSet.of_list in let { ModelParseResult.models; queries; errors } = parse_models_and_queries_from_configuration ~scheduler ~static_analysis_configuration ~taint_configuration:taint_configuration_shared_memory ~resolution ~source_sink_filter:taint_configuration.source_sink_filter ~callables:(Some callables_hashset) ~stubs:stubs_hashset in Statistics.performance ~name:"Parsed taint models" ~phase_name:"Parsing taint models" ~timer (); let models, errors = match queries with | [] -> models, errors | _ -> Log.info "Generating models from model queries..."; let timer = Timer.start () in let verbose = Option.is_some taint_configuration.dump_model_query_results_path in let model_query_results, model_query_errors = ModelQueryExecution.generate_models_from_queries ~resolution ~scheduler ~class_hierarchy_graph ~verbose ~source_sink_filter:(Some taint_configuration.source_sink_filter) ~callables_and_stubs: (Interprocedural.FetchCallables.get_callables_and_stubs initial_callables) ~stubs:stubs_hashset queries in let () = match taint_configuration.dump_model_query_results_path with | Some path -> ModelQueryExecution.DumpModelQueryResults.dump_to_file ~model_query_results ~path | None -> () in let () = ModelVerificationError.verify_models_and_dsl model_query_errors static_analysis_configuration.verify_dsl in let errors = List.append errors model_query_errors in let models = model_query_results |> ModelQueryExecution.ModelQueryRegistryMap.get_registry ~model_join:Model.join_user_models |> Registry.merge ~join:Model.join_user_models models in Statistics.performance ~name:"Generated models from model queries" ~phase_name:"Generating models from model queries" ~timer (); models, errors in let models = ClassModels.infer ~environment ~user_models:models |> Registry.merge ~join:Model.join_user_models models in let models = MissingFlow.add_obscure_models ~static_analysis_configuration ~environment ~stubs:stubs_hashset ~initial_models:models in { ModelParseResult.models; queries = []; errors } (** Aggressively remove things we do not need anymore from the shared memory. *) let purge_shared_memory ~environment ~qualifiers = let ast_environment = Analysis.TypeEnvironment.ast_environment environment in Analysis.AstEnvironment.remove_sources ast_environment qualifiers; Memory.SharedMemory.collect `aggressive; () let run_taint_analysis ~static_analysis_configuration: ({ Configuration.StaticAnalysis.configuration; repository_root; inline_decorators; use_cache; limit_entrypoints; _; } as static_analysis_configuration) ~build_system ~scheduler () = try let taint_configuration, taint_configuration_shared_memory = initialize_configuration ~static_analysis_configuration in (* Collect decorators to skip before type-checking because decorator inlining happens in an early phase of type-checking and needs to know which decorators to skip. *) let () = parse_and_save_decorators_to_skip ~inline_decorators configuration in let cache = Cache.load ~scheduler ~configuration ~taint_configuration ~enabled:use_cache in let environment = type_check ~scheduler ~configuration ~cache in let qualifiers = Analysis.TypeEnvironment.module_tracker environment |> Analysis.ModuleTracker.read_only |> Analysis.ModuleTracker.ReadOnly.tracked_explicit_modules in let read_only_environment = Analysis.TypeEnvironment.read_only environment in let class_hierarchy_graph = Cache.class_hierarchy_graph cache (fun () -> let timer = Timer.start () in let () = Log.info "Computing class hierarchy graph..." in let class_hierarchy_graph = Interprocedural.ClassHierarchyGraph.Heap.from_qualifiers ~scheduler ~environment:read_only_environment ~qualifiers in Statistics.performance ~name:"Computed class hierarchy graph" ~phase_name:"Computing class hierarchy graph" ~timer (); class_hierarchy_graph) in let class_interval_graph = let timer = Timer.start () in let () = Log.info "Computing class intervals..." in let class_interval_graph = Interprocedural.ClassIntervalSetGraph.Heap.from_class_hierarchy class_hierarchy_graph |> Interprocedural.ClassIntervalSetGraph.SharedMemory.from_heap in Statistics.performance ~name:"Computed class intervals" ~phase_name:"Computing class intervals" ~timer (); class_interval_graph in let initial_callables = Cache.initial_callables cache (fun () -> let timer = Timer.start () in let () = Log.info "Fetching initial callables to analyze..." in let initial_callables = Interprocedural.FetchCallables.from_qualifiers ~scheduler ~configuration ~environment:read_only_environment ~include_unit_tests:false ~qualifiers in Statistics.performance ~name:"Fetched initial callables to analyze" ~phase_name:"Fetching initial callables to analyze" ~timer (); initial_callables) in (* Save the cache here, in case there is a model verification error. *) let () = Cache.save cache in let { ModelParseResult.models = initial_models; errors = model_verification_errors; _ } = initialize_models ~scheduler ~static_analysis_configuration ~taint_configuration ~taint_configuration_shared_memory ~class_hierarchy_graph: (Interprocedural.ClassHierarchyGraph.SharedMemory.from_heap class_hierarchy_graph) ~environment:(Analysis.TypeEnvironment.read_only environment) ~initial_callables in let module_tracker = environment |> Analysis.TypeEnvironment.read_only |> Analysis.TypeEnvironment.ReadOnly.module_tracker in let timer = Timer.start () in let { Interprocedural.OverrideGraph.override_graph_heap; override_graph_shared_memory; skipped_overrides; } = Cache.override_graph cache (fun () -> Log.info "Computing overrides..."; let overrides = Interprocedural.OverrideGraph.build_whole_program_overrides ~static_analysis_configuration ~scheduler ~environment:(Analysis.TypeEnvironment.read_only environment) ~include_unit_tests:false ~skip_overrides:(Registry.skip_overrides initial_models) ~maximum_overrides: (TaintConfiguration.maximum_overrides_to_analyze taint_configuration) ~qualifiers in Statistics.performance ~name:"Overrides computed" ~phase_name:"Computing overrides" ~timer (); overrides) in Log.info "Building call graph..."; let timer = Timer.start () in let { Interprocedural.CallGraph.whole_program_call_graph; define_call_graphs } = Interprocedural.CallGraph.build_whole_program_call_graph ~scheduler ~static_analysis_configuration ~environment:(Analysis.TypeEnvironment.read_only environment) ~override_graph:override_graph_shared_memory ~store_shared_memory:true ~attribute_targets:(Registry.object_targets initial_models) ~skip_analysis_targets:(Registry.skip_analysis initial_models) ~callables:(Interprocedural.FetchCallables.get_non_stub_callables initial_callables) in Statistics.performance ~name:"Call graph built" ~phase_name:"Building call graph" ~timer (); let prune_method = if limit_entrypoints then let entrypoint_references = Registry.entrypoints initial_models in let () = Log.info "Pruning call graph by the following entrypoints: %s" ([%show: Target.t list] entrypoint_references) in Interprocedural.DependencyGraph.PruneMethod.Entrypoints entrypoint_references else Interprocedural.DependencyGraph.PruneMethod.Internals in Log.info "Computing dependencies..."; let timer = Timer.start () in let { Interprocedural.DependencyGraph.dependency_graph; override_targets; callables_kept; callables_to_analyze; } = Interprocedural.DependencyGraph.build_whole_program_dependency_graph ~static_analysis_configuration ~prune:prune_method ~initial_callables ~call_graph:whole_program_call_graph ~overrides:override_graph_heap in Statistics.performance ~name:"Computed dependencies" ~phase_name:"Computing dependencies" ~timer (); let initial_models = MissingFlow.add_unknown_callee_models ~static_analysis_configuration ~call_graph:whole_program_call_graph ~initial_models in Log.info "Purging shared memory..."; let timer = Timer.start () in let () = purge_shared_memory ~environment ~qualifiers in Statistics.performance ~name:"Purged shared memory" ~phase_name:"Purging shared memory" ~timer (); let () = Cache.save cache in Log.info "Analysis fixpoint started for %d overrides and %d functions..." (List.length override_targets) (List.length callables_kept); let fixpoint_timer = Timer.start () in let fixpoint_state = Taint.Fixpoint.compute ~scheduler ~type_environment:(Analysis.TypeEnvironment.read_only environment) ~override_graph:override_graph_shared_memory ~dependency_graph ~context: { Taint.Fixpoint.Context.taint_configuration = taint_configuration_shared_memory; type_environment = Analysis.TypeEnvironment.read_only environment; class_interval_graph; define_call_graphs; } ~initial_callables:(Interprocedural.FetchCallables.get_non_stub_callables initial_callables) ~stubs:(Interprocedural.FetchCallables.get_stubs initial_callables) ~override_targets ~callables_to_analyze ~initial_models ~max_iterations:100 ~epoch:Taint.Fixpoint.Epoch.initial in let filename_lookup path_reference = match Server.PathLookup.instantiate_path_with_build_system ~build_system ~module_tracker path_reference with | None -> None | Some full_path -> let root = Option.value repository_root ~default:configuration.local_root in PyrePath.get_relative_to_root ~root ~path:(PyrePath.create_absolute full_path) in let callables = Target.Set.of_list (List.rev_append (Registry.targets initial_models) callables_to_analyze) in Log.info "Post-processing issues for multi-source rules..."; let timer = Timer.start () in let () = MultiSourcePostProcessing.update_multi_source_issues ~taint_configuration ~callables:callables_to_analyze ~fixpoint_state in Statistics.performance ~name:"Finished issue post-processing for multi-source rules" ~phase_name:"Post-processing issues for multi-source rules" ~timer (); let summary = Reporting.report ~scheduler ~static_analysis_configuration ~taint_configuration:taint_configuration_shared_memory ~filename_lookup ~override_graph:override_graph_shared_memory ~callables ~skipped_overrides ~model_verification_errors ~fixpoint_timer ~fixpoint_state in Yojson.Safe.pretty_to_string (`List summary) |> Log.print "%s" with | (TaintConfiguration.TaintConfigurationError _ | ModelVerificationError.ModelVerificationErrors _) as exn -> raise exn | exn -> (* The backtrace is lost if the exception is caught at the top level, because of `Lwt`. * Let's print the exception here to ease debugging. *) Log.log_exception "Taint analysis failed." exn (Worker.exception_backtrace exn); raise exn
null
https://raw.githubusercontent.com/facebook/pyre-check/d9795d776eafc93b0e51bbb5238ca2f1515a8aed/source/interprocedural_analyses/taint/taintAnalysis.ml
ocaml
TaintAnalysis: this is the entry point of the taint analysis. In order to save time, sanity check models before starting the analysis. * Perform a full type check and build a type environment. In order to get an accurate call graph and type information, we need to ensure that we schedule a type check for external files. * Aggressively remove things we do not need anymore from the shared memory. Collect decorators to skip before type-checking because decorator inlining happens in an early phase of type-checking and needs to know which decorators to skip. Save the cache here, in case there is a model verification error. The backtrace is lost if the exception is caught at the top level, because of `Lwt`. * Let's print the exception here to ease debugging.
* 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. *) open Core open Pyre open Taint module Target = Interprocedural.Target let initialize_configuration ~static_analysis_configuration: { Configuration.StaticAnalysis.configuration = { taint_model_paths; _ }; rule_filter; source_filter; sink_filter; transform_filter; find_missing_flows; dump_model_query_results; maximum_model_source_tree_width; maximum_model_sink_tree_width; maximum_model_tito_tree_width; maximum_tree_depth_after_widening; maximum_return_access_path_width; maximum_return_access_path_depth_after_widening; maximum_tito_collapse_depth; maximum_tito_positions; maximum_overrides_to_analyze; maximum_trace_length; maximum_tito_depth; _; } = Log.info "Verifying model syntax and configuration."; let timer = Timer.start () in let taint_configuration = let open Core.Result in TaintConfiguration.from_taint_model_paths taint_model_paths >>= TaintConfiguration.with_command_line_options ~rule_filter ~source_filter ~sink_filter ~transform_filter ~find_missing_flows ~dump_model_query_results_path:dump_model_query_results ~maximum_model_source_tree_width ~maximum_model_sink_tree_width ~maximum_model_tito_tree_width ~maximum_tree_depth_after_widening ~maximum_return_access_path_width ~maximum_return_access_path_depth_after_widening ~maximum_tito_collapse_depth ~maximum_tito_positions ~maximum_overrides_to_analyze ~maximum_trace_length ~maximum_tito_depth |> TaintConfiguration.exception_on_error in let taint_configuration_shared_memory = TaintConfiguration.SharedMemory.from_heap taint_configuration in let () = ModelParser.get_model_sources ~paths:taint_model_paths |> List.iter ~f:(fun (path, source) -> ModelParser.verify_model_syntax ~path ~source) in let () = Statistics.performance ~name:"Verified model syntax and configuration" ~phase_name:"Verifying model syntax and configuration" ~timer () in taint_configuration, taint_configuration_shared_memory let parse_and_save_decorators_to_skip ~inline_decorators { Configuration.Analysis.taint_model_paths; _ } = Analysis.InlineDecorator.set_should_inline_decorators inline_decorators; if inline_decorators then ( let timer = Timer.start () in Log.info "Getting decorators to skip when inlining..."; let model_sources = ModelParser.get_model_sources ~paths:taint_model_paths in let decorators_to_skip = List.concat_map model_sources ~f:(fun (path, source) -> Analysis.InlineDecorator.decorators_to_skip ~path source) in List.iter decorators_to_skip ~f:(fun decorator -> Analysis.InlineDecorator.DecoratorsToSkip.add decorator decorator); Statistics.performance ~name:"Getting decorators to skip when inlining" ~phase_name:"Getting decorators to skip when inlining" ~timer ()) let type_check ~scheduler ~configuration ~cache = Cache.type_environment cache (fun () -> Log.info "Starting type checking..."; let configuration = { configuration with Configuration.Analysis.analyze_external_sources = true } in let errors_environment = Analysis.EnvironmentControls.create ~populate_call_graph:false configuration |> Analysis.ErrorsEnvironment.create in let type_environment = Analysis.ErrorsEnvironment.type_environment errors_environment in let () = Analysis.ErrorsEnvironment.project_qualifiers errors_environment |> Analysis.TypeEnvironment.populate_for_modules ~scheduler type_environment in type_environment) let parse_models_and_queries_from_sources ~taint_configuration ~scheduler ~resolution ~source_sink_filter ~callables ~stubs sources = TODO(T117715045 ): Do not pass all and stubs explicitly to map_reduce , * since this will marshal - ed between processes and hence is costly . * since this will marshal-ed between processes and hence is costly. *) let map state sources = let taint_configuration = TaintConfiguration.SharedMemory.get taint_configuration in List.fold sources ~init:state ~f:(fun state (path, source) -> ModelParser.parse ~resolution ~path ~source ~taint_configuration ~source_sink_filter:(Some source_sink_filter) ~callables ~stubs () |> ModelParseResult.join state) in Scheduler.map_reduce scheduler ~policy: (Scheduler.Policy.fixed_chunk_count ~minimum_chunks_per_worker:1 ~minimum_chunk_size:1 ~preferred_chunks_per_worker:1 ()) ~initial:ModelParseResult.empty ~map ~reduce:ModelParseResult.join ~inputs:sources () let parse_models_and_queries_from_configuration ~scheduler ~static_analysis_configuration: { Configuration.StaticAnalysis.verify_models; configuration = { taint_model_paths; _ }; _ } ~taint_configuration ~resolution ~source_sink_filter ~callables ~stubs = let ({ ModelParseResult.errors; _ } as parse_result) = ModelParser.get_model_sources ~paths:taint_model_paths |> parse_models_and_queries_from_sources ~taint_configuration ~scheduler ~resolution ~source_sink_filter ~callables ~stubs in let () = ModelVerificationError.verify_models_and_dsl errors verify_models in parse_result let initialize_models ~scheduler ~static_analysis_configuration ~taint_configuration ~taint_configuration_shared_memory ~class_hierarchy_graph ~environment ~initial_callables = let open TaintConfiguration.Heap in let resolution = Analysis.TypeEnvironment.ReadOnly.global_resolution environment in Log.info "Parsing taint models..."; let timer = Timer.start () in let callables_hashset = initial_callables |> Interprocedural.FetchCallables.get_non_stub_callables |> Target.HashSet.of_list in let stubs_hashset = initial_callables |> Interprocedural.FetchCallables.get_stubs |> Target.HashSet.of_list in let { ModelParseResult.models; queries; errors } = parse_models_and_queries_from_configuration ~scheduler ~static_analysis_configuration ~taint_configuration:taint_configuration_shared_memory ~resolution ~source_sink_filter:taint_configuration.source_sink_filter ~callables:(Some callables_hashset) ~stubs:stubs_hashset in Statistics.performance ~name:"Parsed taint models" ~phase_name:"Parsing taint models" ~timer (); let models, errors = match queries with | [] -> models, errors | _ -> Log.info "Generating models from model queries..."; let timer = Timer.start () in let verbose = Option.is_some taint_configuration.dump_model_query_results_path in let model_query_results, model_query_errors = ModelQueryExecution.generate_models_from_queries ~resolution ~scheduler ~class_hierarchy_graph ~verbose ~source_sink_filter:(Some taint_configuration.source_sink_filter) ~callables_and_stubs: (Interprocedural.FetchCallables.get_callables_and_stubs initial_callables) ~stubs:stubs_hashset queries in let () = match taint_configuration.dump_model_query_results_path with | Some path -> ModelQueryExecution.DumpModelQueryResults.dump_to_file ~model_query_results ~path | None -> () in let () = ModelVerificationError.verify_models_and_dsl model_query_errors static_analysis_configuration.verify_dsl in let errors = List.append errors model_query_errors in let models = model_query_results |> ModelQueryExecution.ModelQueryRegistryMap.get_registry ~model_join:Model.join_user_models |> Registry.merge ~join:Model.join_user_models models in Statistics.performance ~name:"Generated models from model queries" ~phase_name:"Generating models from model queries" ~timer (); models, errors in let models = ClassModels.infer ~environment ~user_models:models |> Registry.merge ~join:Model.join_user_models models in let models = MissingFlow.add_obscure_models ~static_analysis_configuration ~environment ~stubs:stubs_hashset ~initial_models:models in { ModelParseResult.models; queries = []; errors } let purge_shared_memory ~environment ~qualifiers = let ast_environment = Analysis.TypeEnvironment.ast_environment environment in Analysis.AstEnvironment.remove_sources ast_environment qualifiers; Memory.SharedMemory.collect `aggressive; () let run_taint_analysis ~static_analysis_configuration: ({ Configuration.StaticAnalysis.configuration; repository_root; inline_decorators; use_cache; limit_entrypoints; _; } as static_analysis_configuration) ~build_system ~scheduler () = try let taint_configuration, taint_configuration_shared_memory = initialize_configuration ~static_analysis_configuration in let () = parse_and_save_decorators_to_skip ~inline_decorators configuration in let cache = Cache.load ~scheduler ~configuration ~taint_configuration ~enabled:use_cache in let environment = type_check ~scheduler ~configuration ~cache in let qualifiers = Analysis.TypeEnvironment.module_tracker environment |> Analysis.ModuleTracker.read_only |> Analysis.ModuleTracker.ReadOnly.tracked_explicit_modules in let read_only_environment = Analysis.TypeEnvironment.read_only environment in let class_hierarchy_graph = Cache.class_hierarchy_graph cache (fun () -> let timer = Timer.start () in let () = Log.info "Computing class hierarchy graph..." in let class_hierarchy_graph = Interprocedural.ClassHierarchyGraph.Heap.from_qualifiers ~scheduler ~environment:read_only_environment ~qualifiers in Statistics.performance ~name:"Computed class hierarchy graph" ~phase_name:"Computing class hierarchy graph" ~timer (); class_hierarchy_graph) in let class_interval_graph = let timer = Timer.start () in let () = Log.info "Computing class intervals..." in let class_interval_graph = Interprocedural.ClassIntervalSetGraph.Heap.from_class_hierarchy class_hierarchy_graph |> Interprocedural.ClassIntervalSetGraph.SharedMemory.from_heap in Statistics.performance ~name:"Computed class intervals" ~phase_name:"Computing class intervals" ~timer (); class_interval_graph in let initial_callables = Cache.initial_callables cache (fun () -> let timer = Timer.start () in let () = Log.info "Fetching initial callables to analyze..." in let initial_callables = Interprocedural.FetchCallables.from_qualifiers ~scheduler ~configuration ~environment:read_only_environment ~include_unit_tests:false ~qualifiers in Statistics.performance ~name:"Fetched initial callables to analyze" ~phase_name:"Fetching initial callables to analyze" ~timer (); initial_callables) in let () = Cache.save cache in let { ModelParseResult.models = initial_models; errors = model_verification_errors; _ } = initialize_models ~scheduler ~static_analysis_configuration ~taint_configuration ~taint_configuration_shared_memory ~class_hierarchy_graph: (Interprocedural.ClassHierarchyGraph.SharedMemory.from_heap class_hierarchy_graph) ~environment:(Analysis.TypeEnvironment.read_only environment) ~initial_callables in let module_tracker = environment |> Analysis.TypeEnvironment.read_only |> Analysis.TypeEnvironment.ReadOnly.module_tracker in let timer = Timer.start () in let { Interprocedural.OverrideGraph.override_graph_heap; override_graph_shared_memory; skipped_overrides; } = Cache.override_graph cache (fun () -> Log.info "Computing overrides..."; let overrides = Interprocedural.OverrideGraph.build_whole_program_overrides ~static_analysis_configuration ~scheduler ~environment:(Analysis.TypeEnvironment.read_only environment) ~include_unit_tests:false ~skip_overrides:(Registry.skip_overrides initial_models) ~maximum_overrides: (TaintConfiguration.maximum_overrides_to_analyze taint_configuration) ~qualifiers in Statistics.performance ~name:"Overrides computed" ~phase_name:"Computing overrides" ~timer (); overrides) in Log.info "Building call graph..."; let timer = Timer.start () in let { Interprocedural.CallGraph.whole_program_call_graph; define_call_graphs } = Interprocedural.CallGraph.build_whole_program_call_graph ~scheduler ~static_analysis_configuration ~environment:(Analysis.TypeEnvironment.read_only environment) ~override_graph:override_graph_shared_memory ~store_shared_memory:true ~attribute_targets:(Registry.object_targets initial_models) ~skip_analysis_targets:(Registry.skip_analysis initial_models) ~callables:(Interprocedural.FetchCallables.get_non_stub_callables initial_callables) in Statistics.performance ~name:"Call graph built" ~phase_name:"Building call graph" ~timer (); let prune_method = if limit_entrypoints then let entrypoint_references = Registry.entrypoints initial_models in let () = Log.info "Pruning call graph by the following entrypoints: %s" ([%show: Target.t list] entrypoint_references) in Interprocedural.DependencyGraph.PruneMethod.Entrypoints entrypoint_references else Interprocedural.DependencyGraph.PruneMethod.Internals in Log.info "Computing dependencies..."; let timer = Timer.start () in let { Interprocedural.DependencyGraph.dependency_graph; override_targets; callables_kept; callables_to_analyze; } = Interprocedural.DependencyGraph.build_whole_program_dependency_graph ~static_analysis_configuration ~prune:prune_method ~initial_callables ~call_graph:whole_program_call_graph ~overrides:override_graph_heap in Statistics.performance ~name:"Computed dependencies" ~phase_name:"Computing dependencies" ~timer (); let initial_models = MissingFlow.add_unknown_callee_models ~static_analysis_configuration ~call_graph:whole_program_call_graph ~initial_models in Log.info "Purging shared memory..."; let timer = Timer.start () in let () = purge_shared_memory ~environment ~qualifiers in Statistics.performance ~name:"Purged shared memory" ~phase_name:"Purging shared memory" ~timer (); let () = Cache.save cache in Log.info "Analysis fixpoint started for %d overrides and %d functions..." (List.length override_targets) (List.length callables_kept); let fixpoint_timer = Timer.start () in let fixpoint_state = Taint.Fixpoint.compute ~scheduler ~type_environment:(Analysis.TypeEnvironment.read_only environment) ~override_graph:override_graph_shared_memory ~dependency_graph ~context: { Taint.Fixpoint.Context.taint_configuration = taint_configuration_shared_memory; type_environment = Analysis.TypeEnvironment.read_only environment; class_interval_graph; define_call_graphs; } ~initial_callables:(Interprocedural.FetchCallables.get_non_stub_callables initial_callables) ~stubs:(Interprocedural.FetchCallables.get_stubs initial_callables) ~override_targets ~callables_to_analyze ~initial_models ~max_iterations:100 ~epoch:Taint.Fixpoint.Epoch.initial in let filename_lookup path_reference = match Server.PathLookup.instantiate_path_with_build_system ~build_system ~module_tracker path_reference with | None -> None | Some full_path -> let root = Option.value repository_root ~default:configuration.local_root in PyrePath.get_relative_to_root ~root ~path:(PyrePath.create_absolute full_path) in let callables = Target.Set.of_list (List.rev_append (Registry.targets initial_models) callables_to_analyze) in Log.info "Post-processing issues for multi-source rules..."; let timer = Timer.start () in let () = MultiSourcePostProcessing.update_multi_source_issues ~taint_configuration ~callables:callables_to_analyze ~fixpoint_state in Statistics.performance ~name:"Finished issue post-processing for multi-source rules" ~phase_name:"Post-processing issues for multi-source rules" ~timer (); let summary = Reporting.report ~scheduler ~static_analysis_configuration ~taint_configuration:taint_configuration_shared_memory ~filename_lookup ~override_graph:override_graph_shared_memory ~callables ~skipped_overrides ~model_verification_errors ~fixpoint_timer ~fixpoint_state in Yojson.Safe.pretty_to_string (`List summary) |> Log.print "%s" with | (TaintConfiguration.TaintConfigurationError _ | ModelVerificationError.ModelVerificationErrors _) as exn -> raise exn | exn -> Log.log_exception "Taint analysis failed." exn (Worker.exception_backtrace exn); raise exn
414271664a54e419a4d0e3007510d1a26d388092d2efc5842bece593f9fa2444
ghcjs/ghcjs-boot
text001.hs
Bug report 28 May 99 When compiled with ghc-4.02 , everything 's fine , it outputs " Value 7 " as expected . But compiled with ghc - pre-4.03 it yields this error message . Fail : Prelude.read : no parse When compiled with ghc-4.02, everything's fine, it outputs "Value 7" as expected. But compiled with ghc-pre-4.03 it yields this error message. Fail: Prelude.read: no parse -} module Main where data Msg = Value Int | Inc deriving (Show, Read) main = do let v = read "Value 7"::Msg print v
null
https://raw.githubusercontent.com/ghcjs/ghcjs-boot/8c549931da27ba9e607f77195208ec156c840c8a/boot/base/tests/text001.hs
haskell
Bug report 28 May 99 When compiled with ghc-4.02 , everything 's fine , it outputs " Value 7 " as expected . But compiled with ghc - pre-4.03 it yields this error message . Fail : Prelude.read : no parse When compiled with ghc-4.02, everything's fine, it outputs "Value 7" as expected. But compiled with ghc-pre-4.03 it yields this error message. Fail: Prelude.read: no parse -} module Main where data Msg = Value Int | Inc deriving (Show, Read) main = do let v = read "Value 7"::Msg print v
2b87f86dadc7dd39a49bb1068d4239e91e78b9e532306d29d54f78b66ca8210c
vkz/PLAI
type-checker.rkt
#lang plai-typed (define-type Type [numT] [boolT] [funT (arg : Type) (ret : Type)]) (define-type-alias TyEnv (listof Binding)) (define extend-ty-env cons) (define-type Binding [bound (name : symbol) (type : Type)]) (define bind bound) (define lookup (lambda ([id : symbol] [env : TyEnv]) (cond [(empty? env) (error id "Unbound identifier: ")] [(symbol=? id (bound-name (first env))) (bound-type (first env))] [else (lookup id (rest env))]))) (define-type TyExprC [numC (n : number)] [boolC (n : boolean)] [idC (s : symbol)] [ifC (test : TyExprC) (th : TyExprC) (el : TyExprC)] [appC (fun : TyExprC) (arg : TyExprC)] [plusC (l : TyExprC) (r : TyExprC)] [multC (l : TyExprC) (r : TyExprC)] [lamC (arg : symbol) (argT : Type) (retT : Type) (body : TyExprC)] [recC (f : symbol) (a : symbol) (aT : Type) (rT : Type) (b : TyExprC) (u : TyExprC)]) (define (tc [expr : TyExprC] [tenv : TyEnv]) : Type (type-case TyExprC expr [numC (n) (numT)] [boolC (n) (boolT)] [idC (n) (lookup n tenv)] [plusC (l r) (let ([lt (tc l tenv)] [rt (tc r tenv)]) (if (and (numT? lt) (numT? rt)) (numT) (error 'tc "+ not both numbers")))] [multC (l r) (let ([lt (tc l tenv)] [rt (tc r tenv)]) (if (and (numT? lt) (numT? rt)) (numT) (error 'tc "* not both numbers")))] [appC (f a) (let ([ft (tc f tenv)] [at (tc a tenv)]) (cond [(not (funT? ft)) (error 'tc "not a function")] [(not (equal? (funT-arg ft) at)) (error 'tc "app arg mismatch")] [else (funT-ret ft)]))] [lamC (a argT retT b) (if (equal? (tc b (extend-ty-env (bind a argT) tenv)) retT) (funT argT retT) (error 'lam "lam type mismatch"))] [recC (f a aT rT b u) (let ([extended-env (extend-ty-env (bind f (funT aT rT)) tenv)]) (cond [(not (equal? rT (tc b (extend-ty-env (bind a aT) extended-env)))) (error 'tc "body return type not correct")] [else (tc u extended-env)]))] [ifC (t th el) (let ([tht (tc th tenv)] [elt (tc el tenv)]) (cond [(not (boolT? (tc t tenv))) (error 'tc "not boolean in test clause of if")] [(not (equal? tht elt)) (error 'tc "type mismatch in if")] [else tht]))]))
null
https://raw.githubusercontent.com/vkz/PLAI/3a7dc604dab78f4ebcfa6f88d03242cb3f7f1113/type-checker.rkt
racket
#lang plai-typed (define-type Type [numT] [boolT] [funT (arg : Type) (ret : Type)]) (define-type-alias TyEnv (listof Binding)) (define extend-ty-env cons) (define-type Binding [bound (name : symbol) (type : Type)]) (define bind bound) (define lookup (lambda ([id : symbol] [env : TyEnv]) (cond [(empty? env) (error id "Unbound identifier: ")] [(symbol=? id (bound-name (first env))) (bound-type (first env))] [else (lookup id (rest env))]))) (define-type TyExprC [numC (n : number)] [boolC (n : boolean)] [idC (s : symbol)] [ifC (test : TyExprC) (th : TyExprC) (el : TyExprC)] [appC (fun : TyExprC) (arg : TyExprC)] [plusC (l : TyExprC) (r : TyExprC)] [multC (l : TyExprC) (r : TyExprC)] [lamC (arg : symbol) (argT : Type) (retT : Type) (body : TyExprC)] [recC (f : symbol) (a : symbol) (aT : Type) (rT : Type) (b : TyExprC) (u : TyExprC)]) (define (tc [expr : TyExprC] [tenv : TyEnv]) : Type (type-case TyExprC expr [numC (n) (numT)] [boolC (n) (boolT)] [idC (n) (lookup n tenv)] [plusC (l r) (let ([lt (tc l tenv)] [rt (tc r tenv)]) (if (and (numT? lt) (numT? rt)) (numT) (error 'tc "+ not both numbers")))] [multC (l r) (let ([lt (tc l tenv)] [rt (tc r tenv)]) (if (and (numT? lt) (numT? rt)) (numT) (error 'tc "* not both numbers")))] [appC (f a) (let ([ft (tc f tenv)] [at (tc a tenv)]) (cond [(not (funT? ft)) (error 'tc "not a function")] [(not (equal? (funT-arg ft) at)) (error 'tc "app arg mismatch")] [else (funT-ret ft)]))] [lamC (a argT retT b) (if (equal? (tc b (extend-ty-env (bind a argT) tenv)) retT) (funT argT retT) (error 'lam "lam type mismatch"))] [recC (f a aT rT b u) (let ([extended-env (extend-ty-env (bind f (funT aT rT)) tenv)]) (cond [(not (equal? rT (tc b (extend-ty-env (bind a aT) extended-env)))) (error 'tc "body return type not correct")] [else (tc u extended-env)]))] [ifC (t th el) (let ([tht (tc th tenv)] [elt (tc el tenv)]) (cond [(not (boolT? (tc t tenv))) (error 'tc "not boolean in test clause of if")] [(not (equal? tht elt)) (error 'tc "type mismatch in if")] [else tht]))]))
333521087fbb4665ac1bc78bd99199e5246af796aa0207e419594f01b0c224f5
YoshikuniJujo/test_haskell
makeEnumVkBlendOp.hs
# OPTIONS_GHC -Wall -fno - warn - tabs # module Main where import MakeEnum main :: IO () main = makeEnum "/usr/include/vulkan/vulkan_core.h" "BlendOp" "VkBlendOp" ""
null
https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/d90cb245f0622524c3426635ab0080e8aa80b60b/themes/gui/vulkan/try-my-vulkan/tools/makeEnumVkBlendOp.hs
haskell
# OPTIONS_GHC -Wall -fno - warn - tabs # module Main where import MakeEnum main :: IO () main = makeEnum "/usr/include/vulkan/vulkan_core.h" "BlendOp" "VkBlendOp" ""
101ce1932b34a2e04f50aa9cd7cba61dcdfe1d6036675a72b314ecc9cdc3efa5
mirage/ca-certs-nss
ca_certs_nss.ml
module Make (C : Mirage_clock.PCLOCK) = struct let authenticator = let tas = List.fold_left (fun acc data -> Result.bind acc (fun acc -> Result.map (fun cert -> cert :: acc) (X509.Certificate.decode_der (Cstruct.of_string data)))) (Ok []) Trust_anchor.certificates and time () = Some (Ptime.v (C.now_d_ps ())) in fun ?crls ?allowed_hashes () -> Result.map (X509.Authenticator.chain_of_trust ~time ?crls ?allowed_hashes) tas end
null
https://raw.githubusercontent.com/mirage/ca-certs-nss/306dfb17b45fca4fc44b6987c06d2a7971d51daa/lib/ca_certs_nss.ml
ocaml
module Make (C : Mirage_clock.PCLOCK) = struct let authenticator = let tas = List.fold_left (fun acc data -> Result.bind acc (fun acc -> Result.map (fun cert -> cert :: acc) (X509.Certificate.decode_der (Cstruct.of_string data)))) (Ok []) Trust_anchor.certificates and time () = Some (Ptime.v (C.now_d_ps ())) in fun ?crls ?allowed_hashes () -> Result.map (X509.Authenticator.chain_of_trust ~time ?crls ?allowed_hashes) tas end
0ac0388ea94a34427fd1912a733cbafb8698aabd8150e0ca9975fb0b8140d0e2
discus-lang/ddc
TransInteract.hs
module DDCI.Core.Command.TransInteract ( cmdTransInteract , cmdTransInteractLoop) where import DDCI.Core.Output import DDCI.Core.State import DDC.Driver.Command.Check import DDC.Driver.Command.Trans import DDC.Build.Language import DDC.Core.Fragment import DDC.Core.Simplifier.Parser import DDC.Core.Transform.Reannotate import DDC.Core.Exp.Annot import DDC.Core.Check import DDC.Core.Module import DDC.Data.Pretty import qualified Data.Map.Strict as Map import qualified Data.Set as Set TransInteract -------------------------------------------------------------- -- | Apply the current transform to an expression. cmdTransInteract :: State -> Source -> String -> IO State cmdTransInteract state source str | Language bundle <- stateLanguage state , fragment <- bundleFragment bundle , modules <- bundleModules bundle = cmdParseCheckExp fragment modules Recon False False source str >>= goStore bundle where -- Expression is well-typed. goStore bundle (Just xx, _) = do let xx' = reannotate (\a -> a { annotTail = () }) xx let annot = annotOfExp xx' let t1 = annotType annot let eff1 = annotEffect annot let clo1 = annotClosure annot let hist = TransHistory { historyExp = (xx', t1, eff1, clo1) , historySteps = [] , historyBundle = bundle } return state { stateTransInteract = Just hist } -- Expression had a parse or type error. goStore _ _ = do return state cmdTransInteractLoop :: State -> String -> IO State cmdTransInteractLoop state str | Just hist <- stateTransInteract state , TransHistory (x,t,e,c) steps bundle <- hist , fragment <- bundleFragment bundle , profile <- fragmentProfile fragment = case str of ":back" -> do let steps' = case steps of [] -> [] (_:ss) -> ss putStrLn "Going back: " let x' = case steps' of [] -> x ((xz,_):_) -> xz outDocLn state $ ppr x' let hist' = TransHistory (x,t,e,c) steps' bundle return state { stateTransInteract = Just hist' } ":done" -> do let simps = reverse $ map (indent 4 . ppr . snd) steps outStrLn state "* TRANSFORM SEQUENCE:" mapM_ (outDocLn state) simps return state { stateTransInteract = Nothing } _ -> do let tr = parseSimplifier (fragmentReadName fragment) (SimplifierDetails (bundleMakeNamifierT bundle) (bundleMakeNamifierX bundle) (Map.assocs $ bundleRewriteRules bundle) (Map.elems $ bundleModules bundle)) str let x' = case steps of [] -> x ((xz,_):_) -> xz case tr of Left _err -> do putStrLn "Error parsing simplifier" return state Right tr' -> do let env = modulesEnvX (profilePrimKinds profile) (profilePrimTypes profile) (profilePrimDataDefs profile) (Map.elems $ bundleModules bundle) x_trans <- transExp (Set.member TraceTrans $ stateModes state) profile env (bundleStateInit bundle) tr' x' case x_trans of Nothing -> return state Just x_trans' -> do outDocLn state $ ppr x_trans' let steps' = (x_trans', tr') : steps let hist' = TransHistory (x,t,e,c) steps' bundle return state { stateTransInteract = Just hist' } | otherwise = error "No transformation history!"
null
https://raw.githubusercontent.com/discus-lang/ddc/2baa1b4e2d43b6b02135257677671a83cb7384ac/src/s1/ddc-tools/src/ddci-core/DDCI/Core/Command/TransInteract.hs
haskell
------------------------------------------------------------ | Apply the current transform to an expression. Expression is well-typed. Expression had a parse or type error.
module DDCI.Core.Command.TransInteract ( cmdTransInteract , cmdTransInteractLoop) where import DDCI.Core.Output import DDCI.Core.State import DDC.Driver.Command.Check import DDC.Driver.Command.Trans import DDC.Build.Language import DDC.Core.Fragment import DDC.Core.Simplifier.Parser import DDC.Core.Transform.Reannotate import DDC.Core.Exp.Annot import DDC.Core.Check import DDC.Core.Module import DDC.Data.Pretty import qualified Data.Map.Strict as Map import qualified Data.Set as Set cmdTransInteract :: State -> Source -> String -> IO State cmdTransInteract state source str | Language bundle <- stateLanguage state , fragment <- bundleFragment bundle , modules <- bundleModules bundle = cmdParseCheckExp fragment modules Recon False False source str >>= goStore bundle where goStore bundle (Just xx, _) = do let xx' = reannotate (\a -> a { annotTail = () }) xx let annot = annotOfExp xx' let t1 = annotType annot let eff1 = annotEffect annot let clo1 = annotClosure annot let hist = TransHistory { historyExp = (xx', t1, eff1, clo1) , historySteps = [] , historyBundle = bundle } return state { stateTransInteract = Just hist } goStore _ _ = do return state cmdTransInteractLoop :: State -> String -> IO State cmdTransInteractLoop state str | Just hist <- stateTransInteract state , TransHistory (x,t,e,c) steps bundle <- hist , fragment <- bundleFragment bundle , profile <- fragmentProfile fragment = case str of ":back" -> do let steps' = case steps of [] -> [] (_:ss) -> ss putStrLn "Going back: " let x' = case steps' of [] -> x ((xz,_):_) -> xz outDocLn state $ ppr x' let hist' = TransHistory (x,t,e,c) steps' bundle return state { stateTransInteract = Just hist' } ":done" -> do let simps = reverse $ map (indent 4 . ppr . snd) steps outStrLn state "* TRANSFORM SEQUENCE:" mapM_ (outDocLn state) simps return state { stateTransInteract = Nothing } _ -> do let tr = parseSimplifier (fragmentReadName fragment) (SimplifierDetails (bundleMakeNamifierT bundle) (bundleMakeNamifierX bundle) (Map.assocs $ bundleRewriteRules bundle) (Map.elems $ bundleModules bundle)) str let x' = case steps of [] -> x ((xz,_):_) -> xz case tr of Left _err -> do putStrLn "Error parsing simplifier" return state Right tr' -> do let env = modulesEnvX (profilePrimKinds profile) (profilePrimTypes profile) (profilePrimDataDefs profile) (Map.elems $ bundleModules bundle) x_trans <- transExp (Set.member TraceTrans $ stateModes state) profile env (bundleStateInit bundle) tr' x' case x_trans of Nothing -> return state Just x_trans' -> do outDocLn state $ ppr x_trans' let steps' = (x_trans', tr') : steps let hist' = TransHistory (x,t,e,c) steps' bundle return state { stateTransInteract = Just hist' } | otherwise = error "No transformation history!"
216f45dc9cd7a3dfa3173af7dc633a2bff0e0697f65f4b43c08237cc5f8b4360
tomhanika/conexp-clj
scene_layouts.clj
(ns conexp.gui.draw.scene-layouts "Basic namespace for drawing lattice." (:require [conexp.base :refer :all] [conexp.gui.draw.nodes-and-connections :refer :all] [conexp.gui.draw.scenes :refer :all] [conexp.gui.util :refer :all] [conexp.layouts.base :refer :all] [conexp.layouts.util :refer :all]) (:import [java.awt BorderLayout Color Dimension] [javax.swing JButton JFrame JLabel JPanel] [no.geosoft.cc.graphics GScene GStyle GWindow])) ;;; get diagram from scene (defn get-diagram-from-scene "Returns nodes and lines of a scene." [^GScene scene] (seq (.getChildren scene))) ;;; node and line iterators (defmacro do-nodes "Do whatever with every node on the scene. Redraws the scene afterwards." [[node scene] & body] `(do (doseq [~node (filter node? (get-diagram-from-scene ~scene))] ~@body) (redraw-scene ~scene))) (defmacro do-lines "Do whatever with every connection on the scene. Redraws the scene afterwards." [[line scene] & body] `(do (doseq [~line (filter connection? (get-diagram-from-scene ~scene))] ~@body) (redraw-scene))) ;;; manipulate layout of scene (defn get-layout-from-scene "Returns layout from a scene." [scn] (update-positions (get-data-from-scene scn :layout) (reduce! (fn [hash node] (assoc! hash (get-name node) (position node))) {} (filter node? (get-diagram-from-scene scn))))) (defn fit-scene-to-layout "Adjusts scene such that layout fits on it. Uses stored layout if none is given. Calls :image-changed hook." ([^GScene scene] (fit-scene-to-layout scene (get-layout-from-scene scene))) ([^GScene scene, layout] (do (add-data-to-scene scene :layout layout) (let [[x_min y_min x_max y_max] (enclosing-rectangle (vals (positions layout))), width (- x_max x_min), height (- y_max y_min), width (if (zero? width) 1 width), height (if (zero? height) 1 height)] (.setWorldExtent scene (double (- x_min (* 0.05 width))) (double (- y_min (* 0.05 height))) (double (* 1.10 width)) (double (* 1.10 height))) (.unzoom scene) (call-scene-hook scene :image-changed))))) (defn update-layout-of-scene "Updates layout according to new layout. The underlying lattice must not be changed." [^GScene scene, layout] (do (let [old-layout (-> scene get-layout-from-scene) get-value-fn (fn [L] (if (or (instance? java.util.concurrent.Future (.valuations L)) (instance? clojure.lang.Ref (.valuations L))) (deref (.valuations L)) (.valuations L))) old-value-fn (get-value-fn old-layout)] (if (-> layout get-value-fn empty?) (add-data-to-scene scene :layout (update-valuations layout old-value-fn)) (add-data-to-scene scene :layout layout))) (let [pos (positions layout)] (do-nodes [node scene] (let [[x y] (pos (get-name node))] (move-node-unchecked-to node x y)))))) (defn update-valuations-of-scene "Updates valutions according to new valuation function. The underlying lattice must not be changed." [^GScene scene, layout] (do (add-data-to-scene scene :layout layout) (do-nodes [node scene] (revaluate-node-unchecked node (valuations layout))))) (defn set-layout-of-scene "Sets given layout as current layout of scene." [^GScene scene, layout] (doto scene (.removeAll) (add-nodes-with-connections (positions layout) (connections layout) (annotation layout) (valuations layout)) (add-data-to-scene :layout layout))) ;;; draw nodes with coordinates and connections on a scene (defn ^GScene draw-on-scene "Draws given layout on a GScene and returns it." [layout] (let [wnd (make-window), scn (make-scene wnd)] (doto scn (set-layout-of-scene layout) (fit-scene-to-layout layout)) (doto wnd (.startInteraction (move-interaction scn))) scn)) ;;; nil
null
https://raw.githubusercontent.com/tomhanika/conexp-clj/3cb86b4906864de7254e1f93e1bb263d165373d9/src/main/clojure/conexp/gui/draw/scene_layouts.clj
clojure
get diagram from scene node and line iterators manipulate layout of scene draw nodes with coordinates and connections on a scene
(ns conexp.gui.draw.scene-layouts "Basic namespace for drawing lattice." (:require [conexp.base :refer :all] [conexp.gui.draw.nodes-and-connections :refer :all] [conexp.gui.draw.scenes :refer :all] [conexp.gui.util :refer :all] [conexp.layouts.base :refer :all] [conexp.layouts.util :refer :all]) (:import [java.awt BorderLayout Color Dimension] [javax.swing JButton JFrame JLabel JPanel] [no.geosoft.cc.graphics GScene GStyle GWindow])) (defn get-diagram-from-scene "Returns nodes and lines of a scene." [^GScene scene] (seq (.getChildren scene))) (defmacro do-nodes "Do whatever with every node on the scene. Redraws the scene afterwards." [[node scene] & body] `(do (doseq [~node (filter node? (get-diagram-from-scene ~scene))] ~@body) (redraw-scene ~scene))) (defmacro do-lines "Do whatever with every connection on the scene. Redraws the scene afterwards." [[line scene] & body] `(do (doseq [~line (filter connection? (get-diagram-from-scene ~scene))] ~@body) (redraw-scene))) (defn get-layout-from-scene "Returns layout from a scene." [scn] (update-positions (get-data-from-scene scn :layout) (reduce! (fn [hash node] (assoc! hash (get-name node) (position node))) {} (filter node? (get-diagram-from-scene scn))))) (defn fit-scene-to-layout "Adjusts scene such that layout fits on it. Uses stored layout if none is given. Calls :image-changed hook." ([^GScene scene] (fit-scene-to-layout scene (get-layout-from-scene scene))) ([^GScene scene, layout] (do (add-data-to-scene scene :layout layout) (let [[x_min y_min x_max y_max] (enclosing-rectangle (vals (positions layout))), width (- x_max x_min), height (- y_max y_min), width (if (zero? width) 1 width), height (if (zero? height) 1 height)] (.setWorldExtent scene (double (- x_min (* 0.05 width))) (double (- y_min (* 0.05 height))) (double (* 1.10 width)) (double (* 1.10 height))) (.unzoom scene) (call-scene-hook scene :image-changed))))) (defn update-layout-of-scene "Updates layout according to new layout. The underlying lattice must not be changed." [^GScene scene, layout] (do (let [old-layout (-> scene get-layout-from-scene) get-value-fn (fn [L] (if (or (instance? java.util.concurrent.Future (.valuations L)) (instance? clojure.lang.Ref (.valuations L))) (deref (.valuations L)) (.valuations L))) old-value-fn (get-value-fn old-layout)] (if (-> layout get-value-fn empty?) (add-data-to-scene scene :layout (update-valuations layout old-value-fn)) (add-data-to-scene scene :layout layout))) (let [pos (positions layout)] (do-nodes [node scene] (let [[x y] (pos (get-name node))] (move-node-unchecked-to node x y)))))) (defn update-valuations-of-scene "Updates valutions according to new valuation function. The underlying lattice must not be changed." [^GScene scene, layout] (do (add-data-to-scene scene :layout layout) (do-nodes [node scene] (revaluate-node-unchecked node (valuations layout))))) (defn set-layout-of-scene "Sets given layout as current layout of scene." [^GScene scene, layout] (doto scene (.removeAll) (add-nodes-with-connections (positions layout) (connections layout) (annotation layout) (valuations layout)) (add-data-to-scene :layout layout))) (defn ^GScene draw-on-scene "Draws given layout on a GScene and returns it." [layout] (let [wnd (make-window), scn (make-scene wnd)] (doto scn (set-layout-of-scene layout) (fit-scene-to-layout layout)) (doto wnd (.startInteraction (move-interaction scn))) scn)) nil
e3d15454085c8d29312d186feb9b4d156d4c53b7cd32bba9409bbe0bfb2ab784
ocaml-sf/learn-ocaml-corpus
build_forget_to_increment_depth.ml
(* The data values carried by the leaves of a tree. *) let rec elements t xs = match t with | Leaf x -> x :: xs | Fork (t, u) -> elements t (elements u xs) let elements (t : 'a tree) : 'a list = elements t [] (* The depths of the leaves of a tree. *) let rec depths d t ds = match t with | Leaf _ -> d :: ds | Fork (t, u) -> depths (d + 1) t (depths (d + 1) u ds) let depths (t : 'a tree) : depth list = depths 0 t [] (* The elements and depths, combined. *) let spectre (t : 'a tree) : 'a spectre = List.combine (elements t) (depths t) (* A direct definition can also be given. *) (* A facility for reading and consuming the elements of a list. *) let new_input (xs : 'a list) : 'a input = let input, position = ref xs, ref 0 in let peek () = match !input with [] -> None | x :: _ -> Some x and consume () = match !input with [] -> assert false | _ :: xs -> input := xs; incr position and current () = !position in { peek; consume; current } (* Reconstructing a tree from its spectre. *) This is 's solution , which he attributes to Tarjan . It has the structure of an LL parser , that is , a recursive descent parser . It is a recursive function and therefore uses an implicit stack . structure of an LL parser, that is, a recursive descent parser. It is a recursive function and therefore uses an implicit stack. *) let rec tree (depth : int) (input : ('a * int) input) : 'a tree = match input.peek() with | None -> (* Premature end of input. *) raise (InputIsTooShort (input.current())) | Some (x, d) -> (* If this element lies at our expected depth [depth], then we must consume it and make it a [Leaf]. *) if d = depth then begin input.consume(); Leaf x end If this element lies further down than our expected depth , then it must be part of a subtree that we have not yet built , and which has a [ Fork ] at its root . So , we do not consume this element . Instead , we perform two recursive calls ( on our unchanged input ) that build two subtrees [ t1 ] and [ t2 ] at expected depth [ d+1 ] , and we combine them into a single subtree . must be part of a subtree that we have not yet built, and which has a [Fork] at its root. So, we do not consume this element. Instead, we perform two recursive calls (on our unchanged input) that build two subtrees [t1] and [t2] at expected depth [d+1], and we combine them into a single subtree. *) else if d > depth then let t1 = tree depth input in (* wrong *) let t2 = tree depth input in (* wrong *) Fork (t1, t2) else (* We have [d < depth]. This element lies higher than our expected depth. The input is ill-formed. *) raise (InputIsIllFormed (input.current())) let build (depths : 'a spectre) : 'a tree = let input = new_input depths in let t = tree 0 input in match input.peek() with | None -> t | Some _ -> raise (InputIsTooLong (input.current()))
null
https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/spectre/wrong/build_forget_to_increment_depth.ml
ocaml
The data values carried by the leaves of a tree. The depths of the leaves of a tree. The elements and depths, combined. A direct definition can also be given. A facility for reading and consuming the elements of a list. Reconstructing a tree from its spectre. Premature end of input. If this element lies at our expected depth [depth], then we must consume it and make it a [Leaf]. wrong wrong We have [d < depth]. This element lies higher than our expected depth. The input is ill-formed.
let rec elements t xs = match t with | Leaf x -> x :: xs | Fork (t, u) -> elements t (elements u xs) let elements (t : 'a tree) : 'a list = elements t [] let rec depths d t ds = match t with | Leaf _ -> d :: ds | Fork (t, u) -> depths (d + 1) t (depths (d + 1) u ds) let depths (t : 'a tree) : depth list = depths 0 t [] let spectre (t : 'a tree) : 'a spectre = List.combine (elements t) (depths t) let new_input (xs : 'a list) : 'a input = let input, position = ref xs, ref 0 in let peek () = match !input with [] -> None | x :: _ -> Some x and consume () = match !input with [] -> assert false | _ :: xs -> input := xs; incr position and current () = !position in { peek; consume; current } This is 's solution , which he attributes to Tarjan . It has the structure of an LL parser , that is , a recursive descent parser . It is a recursive function and therefore uses an implicit stack . structure of an LL parser, that is, a recursive descent parser. It is a recursive function and therefore uses an implicit stack. *) let rec tree (depth : int) (input : ('a * int) input) : 'a tree = match input.peek() with | None -> raise (InputIsTooShort (input.current())) | Some (x, d) -> if d = depth then begin input.consume(); Leaf x end If this element lies further down than our expected depth , then it must be part of a subtree that we have not yet built , and which has a [ Fork ] at its root . So , we do not consume this element . Instead , we perform two recursive calls ( on our unchanged input ) that build two subtrees [ t1 ] and [ t2 ] at expected depth [ d+1 ] , and we combine them into a single subtree . must be part of a subtree that we have not yet built, and which has a [Fork] at its root. So, we do not consume this element. Instead, we perform two recursive calls (on our unchanged input) that build two subtrees [t1] and [t2] at expected depth [d+1], and we combine them into a single subtree. *) else if d > depth then Fork (t1, t2) else raise (InputIsIllFormed (input.current())) let build (depths : 'a spectre) : 'a tree = let input = new_input depths in let t = tree 0 input in match input.peek() with | None -> t | Some _ -> raise (InputIsTooLong (input.current()))
5bd00783de4af8d9a33946017a9bed360e67b949083fce09a1578598c02a7d44
wadehennessey/wcl
manager.lisp
-*- Mode : Lisp ; Package : XLIB ; Syntax : COMMON - LISP ; ; Lowercase : T -*- ;;; Window Manager Property functions ;;; TEXAS INSTRUMENTS INCORPORATED ;;; P.O. BOX 2909 AUSTIN , TEXAS 78769 ;;; Copyright ( C ) 1987 Texas Instruments Incorporated . ;;; ;;; Permission is granted to any individual or institution to use, copy, modify, ;;; and distribute this software, provided that this complete copyright and ;;; permission notice is maintained, intact, in all copies and supporting ;;; documentation. ;;; Texas Instruments Incorporated provides this software " as is " without ;;; express or implied warranty. ;;; (in-package :xlib) (defun wm-name (window) (declare (type window window)) (declare (values string)) (get-property window :WM_NAME :type :STRING :result-type 'string :transform #'card8->char)) (defsetf wm-name (window) (name) `(set-string-property ,window :WM_NAME ,name)) (defun set-string-property (window property string) (declare (type window window) (type keyword property) (type stringable string)) (change-property window property (string string) :STRING 8 :transform #'char->card8) string) (defun wm-icon-name (window) (declare (type window window)) (declare (values string)) (get-property window :WM_ICON_NAME :type :STRING :result-type 'string :transform #'card8->char)) (defsetf wm-icon-name (window) (name) `(set-string-property ,window :WM_ICON_NAME ,name)) (defun wm-client-machine (window) (declare (type window window)) (declare (values string)) (get-property window :WM_CLIENT_MACHINE :type :STRING :result-type 'string :transform #'card8->char)) (defsetf wm-client-machine (window) (name) `(set-string-property ,window :WM_CLIENT_MACHINE ,name)) (defun get-wm-class (window) (declare (type window window)) (declare (values (or null name-string) (or null class-string))) (let ((value (get-property window :WM_CLASS :type :STRING :result-type 'string :transform #'card8->char))) (declare (type (or null string) value)) (when value (let* ((name-len (position #.(card8->char 0) (the string value))) (name (subseq (the string value) 0 name-len)) (class (subseq (the string value) (1+ name-len) (1- (length value))))) (values (and (plusp (length name)) name) (and (plusp (length class)) class)))))) (defun set-wm-class (window resource-name resource-class) (declare (type window window) (type (or null stringable) resource-name resource-class)) (set-string-property window :WM_CLASS (concatenate 'string (string (or resource-name "")) Remove # . to avoid bug (make-string 1 :initial-element (card8->char 0)) (string (or resource-class "")) Remove # . to avoid (make-string 1 :initial-element (card8->char 0)))) (values)) (defun wm-command (window) ;; Returns a list whose car is the command and ;; whose cdr is the list of arguments (declare (type window window)) (declare (values list)) (do* ((command-string (get-property window :WM_COMMAND :type :STRING :result-type 'string :transform #'card8->char)) (command nil) (start 0 (1+ end)) (end 0) (len (length command-string))) ((>= start len) (nreverse command)) (setq end (position #.(card8->char 0) command-string :start start)) (push (subseq command-string start end) command))) (defsetf wm-command set-wm-command) (defun set-wm-command (window command) Uses PRIN1 inside the ANSI common lisp form WITH - STANDARD - IO - SYNTAX ( or ;; equivalent), with elements of command separated by NULL characters. This ;; enables ;; (with-standard-io-syntax (mapcar #'read-from-string (wm-command window))) ;; to recover a lisp command. (declare (type window window) (type list command)) (set-string-property window :WM_COMMAND (with-output-to-string (stream) (with-standard-io-syntax (dolist (c command) (prin1 c stream) (write-char #.(card8->char 0) stream))))) command) ;;----------------------------------------------------------------------------- ;; WM_HINTS (def-clx-class (wm-hints) (input nil :type (or null (member :off :on))) (initial-state nil :type (or null (member :dont-care :normal :zoom :iconic :inactive))) (icon-pixmap nil :type (or null pixmap)) (icon-window nil :type (or null window)) (icon-x nil :type (or null card16)) (icon-y nil :type (or null card16)) (icon-mask nil :type (or null pixmap)) (window-group nil :type (or null resource-id)) Extension - hook . Exclusive - Or'ed with the FLAGS field ;; may be extended in the future ) (defun wm-hints (window) (declare (type window window)) (declare (values wm-hints)) (let ((prop (get-property window :WM_HINTS :type :WM_HINTS :result-type 'vector))) (when prop (decode-wm-hints prop (window-display window))))) (defsetf wm-hints set-wm-hints) (defun set-wm-hints (window wm-hints) (declare (type window window) (type wm-hints wm-hints)) (declare (values wm-hints)) (change-property window :WM_HINTS (encode-wm-hints wm-hints) :WM_HINTS 32) wm-hints) (defun decode-wm-hints (vector display) (declare (type (simple-vector 9) vector) (type display display)) (declare (values wm-hints)) (let ((input-hint 0) (state-hint 1) (icon-pixmap-hint 2) (icon-window-hint 3) (icon-position-hint 4) (icon-mask-hint 5) (window-group-hint 6)) (let ((flags (aref vector 0)) (hints (make-wm-hints)) (%buffer display)) (declare (type card32 flags) (type wm-hints hints) (type display %buffer)) (setf (wm-hints-flags hints) flags) (when (logbitp input-hint flags) (setf (wm-hints-input hints) (decode-type (member :off :on) (aref vector 1)))) (when (logbitp state-hint flags) (setf (wm-hints-initial-state hints) (decode-type (member :dont-care :normal :zoom :iconic :inactive) (aref vector 2)))) (when (logbitp icon-pixmap-hint flags) (setf (wm-hints-icon-pixmap hints) (decode-type pixmap (aref vector 3)))) (when (logbitp icon-window-hint flags) (setf (wm-hints-icon-window hints) (decode-type window (aref vector 4)))) (when (logbitp icon-position-hint flags) (setf (wm-hints-icon-x hints) (aref vector 5) (wm-hints-icon-y hints) (aref vector 6))) (when (logbitp icon-mask-hint flags) (setf (wm-hints-icon-mask hints) (decode-type pixmap (aref vector 7)))) (when (and (logbitp window-group-hint flags) (> (length vector) 7)) (setf (wm-hints-window-group hints) (aref vector 8))) hints))) (defun encode-wm-hints (wm-hints) (declare (type wm-hints wm-hints)) (declare (values simple-vector)) (let ((input-hint #b1) (state-hint #b10) (icon-pixmap-hint #b100) (icon-window-hint #b1000) (icon-position-hint #b10000) (icon-mask-hint #b100000) (window-group-hint #b1000000) (mask #b1111111) ) (let ((vector (make-array 9 :initial-element 0)) (flags 0)) (declare (type (simple-vector 9) vector) (type card16 flags)) (when (wm-hints-input wm-hints) (setf flags input-hint (aref vector 1) (encode-type (member :off :on) (wm-hints-input wm-hints)))) (when (wm-hints-initial-state wm-hints) (setf flags (logior flags state-hint) (aref vector 2) (encode-type (member :dont-care :normal :zoom :iconic :inactive) (wm-hints-initial-state wm-hints)))) (when (wm-hints-icon-pixmap wm-hints) (setf flags (logior flags icon-pixmap-hint) (aref vector 3) (encode-type pixmap (wm-hints-icon-pixmap wm-hints)))) (when (wm-hints-icon-window wm-hints) (setf flags (logior flags icon-window-hint) (aref vector 4) (encode-type window (wm-hints-icon-window wm-hints)))) (when (and (wm-hints-icon-x wm-hints) (wm-hints-icon-y wm-hints)) (setf flags (logior flags icon-position-hint) (aref vector 5) (encode-type card16 (wm-hints-icon-x wm-hints)) (aref vector 6) (encode-type card16 (wm-hints-icon-y wm-hints)))) (when (wm-hints-icon-mask wm-hints) (setf flags (logior flags icon-mask-hint) (aref vector 7) (encode-type pixmap (wm-hints-icon-mask wm-hints)))) (when (wm-hints-window-group wm-hints) (setf flags (logior flags window-group-hint) (aref vector 8) (wm-hints-window-group wm-hints))) (setf (aref vector 0) (logior flags (logandc2 (wm-hints-flags wm-hints) mask))) vector))) ;;----------------------------------------------------------------------------- ;; WM_SIZE_HINTS (def-clx-class (wm-size-hints) (user-specified-position-p nil :type boolean) ;; True when user specified x y (user-specified-size-p nil :type boolean) ;; True when user specified width height (x nil :type (or null int16)) ;; Obsolete (y nil :type (or null int16)) ;; Obsolete (width nil :type (or null card16)) ;; Obsolete (height nil :type (or null card16)) ;; Obsolete (min-width nil :type (or null card16)) (min-height nil :type (or null card16)) (max-width nil :type (or null card16)) (max-height nil :type (or null card16)) (width-inc nil :type (or null card16)) (height-inc nil :type (or null card16)) (min-aspect nil :type (or null number)) (max-aspect nil :type (or null number)) (base-width nil :type (or null card16)) (base-height nil :type (or null card16)) (win-gravity nil :type (or null win-gravity)) (program-specified-position-p nil :type boolean) ;; True when program specified x y (program-specified-size-p nil :type boolean) ;; True when program specified width height ) (defun wm-normal-hints (window) (declare (type window window)) (declare (values wm-size-hints)) (decode-wm-size-hints (get-property window :WM_NORMAL_HINTS :type :WM_SIZE_HINTS :result-type 'vector))) (defsetf wm-normal-hints set-wm-normal-hints) (defun set-wm-normal-hints (window hints) (declare (type window window) (type wm-size-hints hints)) (declare (values wm-size-hints)) (change-property window :WM_NORMAL_HINTS (encode-wm-size-hints hints) :WM_SIZE_HINTS 32) hints) ;;; OBSOLETE (defun wm-zoom-hints (window) (declare (type window window)) (declare (values wm-size-hints)) (decode-wm-size-hints (get-property window :WM_ZOOM_HINTS :type :WM_SIZE_HINTS :result-type 'vector))) ;;; OBSOLETE (defsetf wm-zoom-hints set-wm-zoom-hints) ;;; OBSOLETE (defun set-wm-zoom-hints (window hints) (declare (type window window) (type wm-size-hints hints)) (declare (values wm-size-hints)) (change-property window :WM_ZOOM_HINTS (encode-wm-size-hints hints) :WM_SIZE_HINTS 32) hints) (defun decode-wm-size-hints (vector) (declare (type (or null (simple-vector *)) vector)) (declare (values (or null wm-size-hints))) (when vector (let ((flags (aref vector 0)) (hints (make-wm-size-hints))) (declare (type card16 flags) (type wm-size-hints hints)) (setf (wm-size-hints-user-specified-position-p hints) (logbitp 0 flags)) (setf (wm-size-hints-user-specified-size-p hints) (logbitp 1 flags)) (setf (wm-size-hints-program-specified-position-p hints) (logbitp 2 flags)) (setf (wm-size-hints-program-specified-size-p hints) (logbitp 3 flags)) (when (logbitp 4 flags) (setf (wm-size-hints-min-width hints) (aref vector 5) (wm-size-hints-min-height hints) (aref vector 6))) (when (logbitp 5 flags) (setf (wm-size-hints-max-width hints) (aref vector 7) (wm-size-hints-max-height hints) (aref vector 8))) (when (logbitp 6 flags) (setf (wm-size-hints-width-inc hints) (aref vector 9) (wm-size-hints-height-inc hints) (aref vector 10))) (when (logbitp 7 flags) (setf (wm-size-hints-min-aspect hints) (/ (aref vector 11) (aref vector 12)) (wm-size-hints-max-aspect hints) (/ (aref vector 13) (aref vector 14)))) (when (> (length vector) 15) This test is for backwards compatibility since old Xlib programs can set a size - hints structure that is too small . See ICCCM . (when (logbitp 8 flags) (setf (wm-size-hints-base-width hints) (aref vector 15) (wm-size-hints-base-height hints) (aref vector 16))) (when (logbitp 9 flags) (setf (wm-size-hints-win-gravity hints) (decode-type (member-vector *win-gravity-vector*) (aref vector 17))))) ;; Obsolete fields (when (or (logbitp 0 flags) (logbitp 2 flags)) (setf (wm-size-hints-x hints) (aref vector 1) (wm-size-hints-y hints) (aref vector 2))) (when (or (logbitp 1 flags) (logbitp 3 flags)) (setf (wm-size-hints-width hints) (aref vector 3) (wm-size-hints-height hints) (aref vector 4))) hints))) (defun encode-wm-size-hints (hints) (declare (type wm-size-hints hints)) (declare (values simple-vector)) (let ((vector (make-array 18 :initial-element 0)) (flags 0)) (declare (type (simple-vector 18) vector) (type card16 flags)) (when (wm-size-hints-user-specified-position-p hints) (setf (ldb (byte 1 0) flags) 1)) (when (wm-size-hints-user-specified-size-p hints) (setf (ldb (byte 1 1) flags) 1)) (when (wm-size-hints-program-specified-position-p hints) (setf (ldb (byte 1 2) flags) 1)) (when (wm-size-hints-program-specified-size-p hints) (setf (ldb (byte 1 3) flags) 1)) (when (and (wm-size-hints-min-width hints) (wm-size-hints-min-height hints)) (setf (ldb (byte 1 4) flags) 1 (aref vector 5) (wm-size-hints-min-width hints) (aref vector 6) (wm-size-hints-min-height hints))) (when (and (wm-size-hints-max-width hints) (wm-size-hints-max-height hints)) (setf (ldb (byte 1 5) flags) 1 (aref vector 7) (wm-size-hints-max-width hints) (aref vector 8) (wm-size-hints-max-height hints))) (when (and (wm-size-hints-width-inc hints) (wm-size-hints-height-inc hints)) (setf (ldb (byte 1 6) flags) 1 (aref vector 9) (wm-size-hints-width-inc hints) (aref vector 10) (wm-size-hints-height-inc hints))) (let ((min-aspect (wm-size-hints-min-aspect hints)) (max-aspect (wm-size-hints-max-aspect hints))) (when (and min-aspect max-aspect) (setf (ldb (byte 1 7) flags) 1 min-aspect (rationalize min-aspect) max-aspect (rationalize max-aspect) (aref vector 11) (numerator min-aspect) (aref vector 12) (denominator min-aspect) (aref vector 13) (numerator max-aspect) (aref vector 14) (denominator max-aspect)))) (when (and (wm-size-hints-base-width hints) (wm-size-hints-base-height hints)) (setf (ldb (byte 1 8) flags) 1 (aref vector 15) (wm-size-hints-base-width hints) (aref vector 16) (wm-size-hints-base-height hints))) (when (wm-size-hints-win-gravity hints) (setf (ldb (byte 1 9) flags) 1 (aref vector 17) (encode-type (member-vector *win-gravity-vector*) (wm-size-hints-win-gravity hints)))) ;; Obsolete fields (when (and (wm-size-hints-x hints) (wm-size-hints-y hints)) (unless (wm-size-hints-user-specified-position-p hints) (setf (ldb (byte 1 2) flags) 1)) (setf (aref vector 1) (wm-size-hints-x hints) (aref vector 2) (wm-size-hints-y hints))) (when (and (wm-size-hints-width hints) (wm-size-hints-height hints)) (unless (wm-size-hints-user-specified-size-p hints) (setf (ldb (byte 1 3) flags) 1)) (setf (aref vector 3) (wm-size-hints-width hints) (aref vector 4) (wm-size-hints-height hints))) (setf (aref vector 0) flags) vector)) ;;----------------------------------------------------------------------------- ;; Icon_Size ;; Use the same intermediate structure as WM_SIZE_HINTS (defun icon-sizes (window) (declare (type window window)) (declare (values wm-size-hints)) (let ((vector (get-property window :WM_ICON_SIZE :type :WM_ICON_SIZE :result-type 'vector))) (declare (type (or null (simple-vector 6)) vector)) (when vector (make-wm-size-hints :min-width (aref vector 0) :min-height (aref vector 1) :max-width (aref vector 2) :max-height (aref vector 3) :width-inc (aref vector 4) :height-inc (aref vector 5))))) (defsetf icon-sizes set-icon-sizes) (defun set-icon-sizes (window wm-size-hints) (declare (type window window) (type wm-size-hints wm-size-hints)) (let ((vector (vector (wm-size-hints-min-width wm-size-hints) (wm-size-hints-min-height wm-size-hints) (wm-size-hints-max-width wm-size-hints) (wm-size-hints-max-height wm-size-hints) (wm-size-hints-width-inc wm-size-hints) (wm-size-hints-height-inc wm-size-hints)))) (change-property window :WM_ICON_SIZE vector :WM_ICON_SIZE 32) wm-size-hints)) ;;----------------------------------------------------------------------------- ;; WM-Protocols (defun wm-protocols (window) (map 'list #'(lambda (id) (atom-name (window-display window) id)) (get-property window :WM_PROTOCOLS :type :ATOM))) (defsetf wm-protocols set-wm-protocols) (defun set-wm-protocols (window protocols) (change-property window :WM_PROTOCOLS (map 'list #'(lambda (atom) (intern-atom (window-display window) atom)) protocols) :ATOM 32) protocols) ;;----------------------------------------------------------------------------- ;; WM-Colormap-windows (defun wm-colormap-windows (window) (values (get-property window :WM_COLORMAP_WINDOWS :type :WINDOW :transform #'(lambda (id) (lookup-window (window-display window) id))))) (defsetf wm-colormap-windows set-wm-colormap-windows) (defun set-wm-colormap-windows (window colormap-windows) (change-property window :WM_COLORMAP_WINDOWS colormap-windows :WINDOW 32 :transform #'window-id) colormap-windows) ;;----------------------------------------------------------------------------- ;; Transient-For (defun transient-for (window) (let ((prop (get-property window :WM_TRANSIENT_FOR :type :WINDOW :result-type 'list))) (and prop (lookup-window (window-display window) (car prop))))) (defsetf transient-for set-transient-for) (defun set-transient-for (window transient) (declare (type window window transient)) (change-property window :WM_TRANSIENT_FOR (list (window-id transient)) :WINDOW 32) transient) ;;----------------------------------------------------------------------------- ;; Set-WM-Properties (defun set-wm-properties (window &rest options &key name icon-name resource-name resource-class command client-machine hints normal-hints zoom-hints ;; the following are used for wm-normal-hints (user-specified-position-p nil usppp) (user-specified-size-p nil usspp) (program-specified-position-p nil psppp) (program-specified-size-p nil psspp) x y width height min-width min-height max-width max-height width-inc height-inc min-aspect max-aspect base-width base-height win-gravity ;; the following are used for wm-hints input initial-state icon-pixmap icon-window icon-x icon-y icon-mask window-group) ;; Set properties for WINDOW. (declare (arglist window &rest options &key name icon-name resource-name resource-class command client-machine hints normal-hints ;; the following are used for wm-normal-hints user-specified-position-p user-specified-size-p program-specified-position-p program-specified-size-p min-width min-height max-width max-height width-inc height-inc min-aspect max-aspect base-width base-height win-gravity ;; the following are used for wm-hints input initial-state icon-pixmap icon-window icon-x icon-y icon-mask window-group)) (declare (type window window) (type (or null stringable) name icon-name resource-name resource-class client-machine) (type (or null list) command) (type (or null wm-hints) hints) (type (or null wm-size-hints) normal-hints zoom-hints) (type boolean user-specified-position-p user-specified-size-p) (type boolean program-specified-position-p program-specified-size-p) (type (or null int16) x y) (type (or null card16) width height min-width min-height max-width max-height width-inc height-inc base-width base-height) (type (or null win-gravity) win-gravity) (type (or null number) min-aspect max-aspect) (type (or null (member :off :on)) input) (type (or null (member :dont-care :normal :zoom :iconic :inactive)) initial-state) (type (or null pixmap) icon-pixmap icon-mask) (type (or null window) icon-window) (type (or null card16) icon-x icon-y) (type (or null resource-id) window-group) (dynamic-extent options)) (when name (setf (wm-name window) name)) (when icon-name (setf (wm-icon-name window) icon-name)) (when client-machine (setf (wm-client-machine window) client-machine)) (when (or resource-name resource-class) (set-wm-class window resource-name resource-class)) (when command (setf (wm-command window) command)) ;; WM-HINTS (if (dolist (arg '(:input :initial-state :icon-pixmap :icon-window :icon-x :icon-y :icon-mask :window-group)) (when (getf options arg) (return t))) (let ((wm-hints (if hints (copy-wm-hints hints) (make-wm-hints)))) (when input (setf (wm-hints-input wm-hints) input)) (when initial-state (setf (wm-hints-initial-state wm-hints) initial-state)) (when icon-pixmap (setf (wm-hints-icon-pixmap wm-hints) icon-pixmap)) (when icon-window (setf (wm-hints-icon-window wm-hints) icon-window)) (when icon-x (setf (wm-hints-icon-x wm-hints) icon-x)) (when icon-y (setf (wm-hints-icon-y wm-hints) icon-y)) (when icon-mask (setf (wm-hints-icon-mask wm-hints) icon-mask)) (when window-group (setf (wm-hints-input wm-hints) window-group)) (setf (wm-hints window) wm-hints)) (when hints (setf (wm-hints window) hints))) ;; WM-NORMAL-HINTS (if (dolist (arg '(:x :y :width :height :min-width :min-height :max-width :max-height :width-inc :height-inc :min-aspect :max-aspect :user-specified-position-p :user-specified-size-p :program-specified-position-p :program-specified-size-p :base-width :base-height :win-gravity)) (when (getf options arg) (return t))) (let ((size (if normal-hints (copy-wm-size-hints normal-hints) (make-wm-size-hints)))) (when x (setf (wm-size-hints-x size) x)) (when y (setf (wm-size-hints-y size) y)) (when width (setf (wm-size-hints-width size) width)) (when height (setf (wm-size-hints-height size) height)) (when min-width (setf (wm-size-hints-min-width size) min-width)) (when min-height (setf (wm-size-hints-min-height size) min-height)) (when max-width (setf (wm-size-hints-max-width size) max-width)) (when max-height (setf (wm-size-hints-max-height size) max-height)) (when width-inc (setf (wm-size-hints-width-inc size) width-inc)) (when height-inc (setf (wm-size-hints-height-inc size) height-inc)) (when min-aspect (setf (wm-size-hints-min-aspect size) min-aspect)) (when max-aspect (setf (wm-size-hints-max-aspect size) max-aspect)) (when base-width (setf (wm-size-hints-base-width size) base-width)) (when base-height (setf (wm-size-hints-base-height size) base-height)) (when win-gravity (setf (wm-size-hints-win-gravity size) win-gravity)) (when usppp (setf (wm-size-hints-user-specified-position-p size) user-specified-position-p)) (when usspp (setf (wm-size-hints-user-specified-size-p size) user-specified-size-p)) (when psppp (setf (wm-size-hints-program-specified-position-p size) program-specified-position-p)) (when psspp (setf (wm-size-hints-program-specified-size-p size) program-specified-size-p)) (setf (wm-normal-hints window) size)) (when normal-hints (setf (wm-normal-hints window) normal-hints))) (when zoom-hints (setf (wm-zoom-hints window) zoom-hints)) ) ;;; OBSOLETE (defun set-standard-properties (window &rest options) (declare (dynamic-extent options)) (apply #'set-wm-properties window options)) ;;----------------------------------------------------------------------------- ;; WM Control (defun iconify-window (window screen) (declare (type window window) (type screen screen)) (let ((root (screen-root screen))) (declare (type window root)) (send-event root :client-message '(:substructure-redirect :substructure-notify) :window window :format 32 :type :WM_CHANGE_STATE :data (list 3)))) (defun withdraw-window (window screen) (declare (type window window) (type screen screen)) (unmap-window window) (let ((root (screen-root screen))) (declare (type window root)) (send-event root :unmap-notify '(:substructure-redirect :substructure-notify) :window window :event-window root :configure-p nil))) ;;----------------------------------------------------------------------------- ;; Colormaps (def-clx-class (standard-colormap (:copier nil) (:predicate nil)) (colormap nil :type (or null colormap)) (base-pixel 0 :type pixel) (max-color nil :type (or null color)) (mult-color nil :type (or null color)) (visual nil :type (or null visual-info)) (kill nil :type (or (member nil :release-by-freeing-colormap) drawable gcontext cursor colormap font))) (defun rgb-colormaps (window property) (declare (type window window) (type (member :RGB_DEFAULT_MAP :RGB_BEST_MAP :RGB_RED_MAP :RGB_GREEN_MAP :RGB_BLUE_MAP) property)) (let ((prop (get-property window property :type :RGB_COLOR_MAP :result-type 'vector))) (declare (type (or null simple-vector) prop)) (when prop (list (make-standard-colormap :colormap (lookup-colormap (window-display window) (aref prop 0)) :base-pixel (aref prop 7) :max-color (make-color :red (card16->rgb-val (aref prop 1)) :green (card16->rgb-val (aref prop 3)) :blue (card16->rgb-val (aref prop 5))) :mult-color (make-color :red (card16->rgb-val (aref prop 2)) :green (card16->rgb-val (aref prop 4)) :blue (card16->rgb-val (aref prop 6))) :visual (and (<= 9 (length prop)) (visual-info (window-display window) (aref prop 8))) :kill (and (<= 10 (length prop)) (let ((killid (aref prop 9))) (if (= killid 1) :release-by-freeing-colormap (lookup-resource-id (window-display window) killid))))))))) (defsetf rgb-colormaps set-rgb-colormaps) (defun set-rgb-colormaps (window property maps) (declare (type window window) (type (member :RGB_DEFAULT_MAP :RGB_BEST_MAP :RGB_RED_MAP :RGB_GREEN_MAP :RGB_BLUE_MAP) property) (type list maps)) (let ((prop (make-array (* 10 (length maps)) :element-type 'card32)) (index -1)) (dolist (map maps) (setf (aref prop (incf index)) (encode-type colormap (standard-colormap-colormap map))) (setf (aref prop (incf index)) (encode-type rgb-val (color-red (standard-colormap-max-color map)))) (setf (aref prop (incf index)) (encode-type rgb-val (color-red (standard-colormap-mult-color map)))) (setf (aref prop (incf index)) (encode-type rgb-val (color-green (standard-colormap-max-color map)))) (setf (aref prop (incf index)) (encode-type rgb-val (color-green (standard-colormap-mult-color map)))) (setf (aref prop (incf index)) (encode-type rgb-val (color-blue (standard-colormap-max-color map)))) (setf (aref prop (incf index)) (encode-type rgb-val (color-blue (standard-colormap-mult-color map)))) (setf (aref prop (incf index)) (standard-colormap-base-pixel map)) (setf (aref prop (incf index)) (visual-info-id (standard-colormap-visual map))) (setf (aref prop (incf index)) (let ((kill (standard-colormap-kill map))) (etypecase kill (symbol (ecase kill ((nil) 0) ((:release-by-freeing-colormap) 1))) (drawable (drawable-id kill)) (gcontext (gcontext-id kill)) (cursor (cursor-id kill)) (colormap (colormap-id kill)) (font (font-id kill)))))) (change-property window property prop :RGB_COLOR_MAP 32))) ;;; OBSOLETE (defun get-standard-colormap (window property) (declare (type window window) (type (member :RGB_DEFAULT_MAP :RGB_BEST_MAP :RGB_RED_MAP :RGB_GREEN_MAP :RGB_BLUE_MAP) property)) (declare (values colormap base-pixel max-color mult-color)) (let ((prop (get-property window property :type :RGB_COLOR_MAP :result-type 'vector))) (declare (type (or null simple-vector) prop)) (when prop (values (lookup-colormap (window-display window) (aref prop 0)) (aref prop 7) ;Base Pixel :green (card16->rgb-val (aref prop 3)) :blue (card16->rgb-val (aref prop 5))) (make-color :red (card16->rgb-val (aref prop 2)) ;Mult color :green (card16->rgb-val (aref prop 4)) :blue (card16->rgb-val (aref prop 6))))))) ;;; OBSOLETE (defun set-standard-colormap (window property colormap base-pixel max-color mult-color) (declare (type window window) (type (member :RGB_DEFAULT_MAP :RGB_BEST_MAP :RGB_RED_MAP :RGB_GREEN_MAP :RGB_BLUE_MAP) property) (type colormap colormap) (type pixel base-pixel) (type color max-color mult-color)) (let ((prop (apply #'vector (encode-type colormap colormap) (encode-type rgb-val (color-red max-color)) (encode-type rgb-val (color-red mult-color)) (encode-type rgb-val (color-green max-color)) (encode-type rgb-val (color-green mult-color)) (encode-type rgb-val (color-blue max-color)) (encode-type rgb-val (color-blue mult-color)) base-pixel))) (change-property window property prop :RGB_COLOR_MAP 32))) ;;----------------------------------------------------------------------------- ;; Cut-Buffers (defun cut-buffer (display &key (buffer 0) (type :STRING) (result-type 'string) (transform #'card8->char) (start 0) end) Return the contents of cut - buffer BUFFER (declare (type display display) (type (integer 0 7) buffer) (type xatom type) (type array-index start) (type (or null array-index) end) (type t result-type) ;a sequence type (type (or null (function (integer) t)) transform)) (declare (values sequence type format bytes-after)) (let* ((root (screen-root (first (display-roots display)))) (property (aref '#(:CUT_BUFFER0 :CUT_BUFFER1 :CUT_BUFFER2 :CUT_BUFFER3 :CUT_BUFFER4 :CUT_BUFFER5 :CUT_BUFFER6 :CUT_BUFFER7) buffer))) (get-property root property :type type :result-type result-type :start start :end end :transform transform))) ;; Implement the following: ( defsetf cut - buffer ( display & key ( buffer 0 ) ( type : string ) ( format 8) ( transform # ' char->card8 ) ( start 0 ) end ) ( data ) ;; In order to avoid having to pass positional parameters to set-cut-buffer, ;; We've got to do the following. WHAT A PAIN... #-clx-ansi-common-lisp (define-setf-method cut-buffer (display &rest option-list) (declare (dynamic-extent option-list)) (do* ((options (copy-list option-list)) (option options (cddr option)) (store (gensym)) (dtemp (gensym)) (temps (list dtemp)) (values (list display))) ((endp option) (values (nreverse temps) (nreverse values) (list store) `(set-cut-buffer ,store ,dtemp ,@options) `(cut-buffer ,@options))) (unless (member (car option) '(:buffer :type :format :start :end :transform)) (error "Keyword arg ~s isn't recognized" (car option))) (let ((x (gensym))) (push x temps) (push (cadr option) values) (setf (cadr option) x)))) (defun #+clx-ansi-common-lisp (setf cut-buffer) #-clx-ansi-common-lisp set-cut-buffer (data display &key (buffer 0) (type :STRING) (format 8) (start 0) end (transform #'char->card8)) (declare (type sequence data) (type display display) (type (integer 0 7) buffer) (type xatom type) (type (member 8 16 32) format) (type array-index start) (type (or null array-index) end) (type (or null (function (integer) t)) transform)) (let* ((root (screen-root (first (display-roots display)))) (property (aref '#(:CUT_BUFFER0 :CUT_BUFFER1 :CUT_BUFFER2 :CUT_BUFFER3 :CUT_BUFFER4 :CUT_BUFFER5 :CUT_BUFFER6 :CUT_BUFFER7) buffer))) (change-property root property data type format :transform transform :start start :end end) data)) (defun rotate-cut-buffers (display &optional (delta 1) (careful-p t)) ;; Positive rotates left, negative rotates right (opposite of actual protocol request). ;; When careful-p, ensure all cut-buffer properties are defined, to prevent errors. (declare (type display display) (type int16 delta) (type boolean careful-p)) (let* ((root (screen-root (first (display-roots display)))) (buffers '#(:cut_buffer0 :cut_buffer1 :cut_buffer2 :cut_buffer3 :cut_buffer4 :cut_buffer5 :cut_buffer6 :cut_buffer7))) (when careful-p (let ((props (list-properties root))) (dotimes (i 8) (unless (member (aref buffers i) props) (setf (cut-buffer display :buffer i) ""))))) (rotate-properties root buffers delta)))
null
https://raw.githubusercontent.com/wadehennessey/wcl/841316ffe06743d4c14b4ed70819bdb39158df6a/src/clx/manager.lisp
lisp
Package : XLIB ; Syntax : COMMON - LISP ; ; Lowercase : T -*- Window Manager Property functions P.O. BOX 2909 Permission is granted to any individual or institution to use, copy, modify, and distribute this software, provided that this complete copyright and permission notice is maintained, intact, in all copies and supporting documentation. express or implied warranty. Returns a list whose car is the command and whose cdr is the list of arguments equivalent), with elements of command separated by NULL characters. This enables (with-standard-io-syntax (mapcar #'read-from-string (wm-command window))) to recover a lisp command. ----------------------------------------------------------------------------- WM_HINTS may be extended in the future ----------------------------------------------------------------------------- WM_SIZE_HINTS True when user specified x y True when user specified width height Obsolete Obsolete Obsolete Obsolete True when program specified x y True when program specified width height OBSOLETE OBSOLETE OBSOLETE Obsolete fields Obsolete fields ----------------------------------------------------------------------------- Icon_Size Use the same intermediate structure as WM_SIZE_HINTS ----------------------------------------------------------------------------- WM-Protocols ----------------------------------------------------------------------------- WM-Colormap-windows ----------------------------------------------------------------------------- Transient-For ----------------------------------------------------------------------------- Set-WM-Properties the following are used for wm-normal-hints the following are used for wm-hints Set properties for WINDOW. the following are used for wm-normal-hints the following are used for wm-hints WM-HINTS WM-NORMAL-HINTS OBSOLETE ----------------------------------------------------------------------------- WM Control ----------------------------------------------------------------------------- Colormaps OBSOLETE Base Pixel Mult color OBSOLETE ----------------------------------------------------------------------------- Cut-Buffers a sequence type Implement the following: In order to avoid having to pass positional parameters to set-cut-buffer, We've got to do the following. WHAT A PAIN... Positive rotates left, negative rotates right (opposite of actual protocol request). When careful-p, ensure all cut-buffer properties are defined, to prevent errors.
TEXAS INSTRUMENTS INCORPORATED AUSTIN , TEXAS 78769 Copyright ( C ) 1987 Texas Instruments Incorporated . Texas Instruments Incorporated provides this software " as is " without (in-package :xlib) (defun wm-name (window) (declare (type window window)) (declare (values string)) (get-property window :WM_NAME :type :STRING :result-type 'string :transform #'card8->char)) (defsetf wm-name (window) (name) `(set-string-property ,window :WM_NAME ,name)) (defun set-string-property (window property string) (declare (type window window) (type keyword property) (type stringable string)) (change-property window property (string string) :STRING 8 :transform #'char->card8) string) (defun wm-icon-name (window) (declare (type window window)) (declare (values string)) (get-property window :WM_ICON_NAME :type :STRING :result-type 'string :transform #'card8->char)) (defsetf wm-icon-name (window) (name) `(set-string-property ,window :WM_ICON_NAME ,name)) (defun wm-client-machine (window) (declare (type window window)) (declare (values string)) (get-property window :WM_CLIENT_MACHINE :type :STRING :result-type 'string :transform #'card8->char)) (defsetf wm-client-machine (window) (name) `(set-string-property ,window :WM_CLIENT_MACHINE ,name)) (defun get-wm-class (window) (declare (type window window)) (declare (values (or null name-string) (or null class-string))) (let ((value (get-property window :WM_CLASS :type :STRING :result-type 'string :transform #'card8->char))) (declare (type (or null string) value)) (when value (let* ((name-len (position #.(card8->char 0) (the string value))) (name (subseq (the string value) 0 name-len)) (class (subseq (the string value) (1+ name-len) (1- (length value))))) (values (and (plusp (length name)) name) (and (plusp (length class)) class)))))) (defun set-wm-class (window resource-name resource-class) (declare (type window window) (type (or null stringable) resource-name resource-class)) (set-string-property window :WM_CLASS (concatenate 'string (string (or resource-name "")) Remove # . to avoid bug (make-string 1 :initial-element (card8->char 0)) (string (or resource-class "")) Remove # . to avoid (make-string 1 :initial-element (card8->char 0)))) (values)) (defun wm-command (window) (declare (type window window)) (declare (values list)) (do* ((command-string (get-property window :WM_COMMAND :type :STRING :result-type 'string :transform #'card8->char)) (command nil) (start 0 (1+ end)) (end 0) (len (length command-string))) ((>= start len) (nreverse command)) (setq end (position #.(card8->char 0) command-string :start start)) (push (subseq command-string start end) command))) (defsetf wm-command set-wm-command) (defun set-wm-command (window command) Uses PRIN1 inside the ANSI common lisp form WITH - STANDARD - IO - SYNTAX ( or (declare (type window window) (type list command)) (set-string-property window :WM_COMMAND (with-output-to-string (stream) (with-standard-io-syntax (dolist (c command) (prin1 c stream) (write-char #.(card8->char 0) stream))))) command) (def-clx-class (wm-hints) (input nil :type (or null (member :off :on))) (initial-state nil :type (or null (member :dont-care :normal :zoom :iconic :inactive))) (icon-pixmap nil :type (or null pixmap)) (icon-window nil :type (or null window)) (icon-x nil :type (or null card16)) (icon-y nil :type (or null card16)) (icon-mask nil :type (or null pixmap)) (window-group nil :type (or null resource-id)) Extension - hook . Exclusive - Or'ed with the FLAGS field ) (defun wm-hints (window) (declare (type window window)) (declare (values wm-hints)) (let ((prop (get-property window :WM_HINTS :type :WM_HINTS :result-type 'vector))) (when prop (decode-wm-hints prop (window-display window))))) (defsetf wm-hints set-wm-hints) (defun set-wm-hints (window wm-hints) (declare (type window window) (type wm-hints wm-hints)) (declare (values wm-hints)) (change-property window :WM_HINTS (encode-wm-hints wm-hints) :WM_HINTS 32) wm-hints) (defun decode-wm-hints (vector display) (declare (type (simple-vector 9) vector) (type display display)) (declare (values wm-hints)) (let ((input-hint 0) (state-hint 1) (icon-pixmap-hint 2) (icon-window-hint 3) (icon-position-hint 4) (icon-mask-hint 5) (window-group-hint 6)) (let ((flags (aref vector 0)) (hints (make-wm-hints)) (%buffer display)) (declare (type card32 flags) (type wm-hints hints) (type display %buffer)) (setf (wm-hints-flags hints) flags) (when (logbitp input-hint flags) (setf (wm-hints-input hints) (decode-type (member :off :on) (aref vector 1)))) (when (logbitp state-hint flags) (setf (wm-hints-initial-state hints) (decode-type (member :dont-care :normal :zoom :iconic :inactive) (aref vector 2)))) (when (logbitp icon-pixmap-hint flags) (setf (wm-hints-icon-pixmap hints) (decode-type pixmap (aref vector 3)))) (when (logbitp icon-window-hint flags) (setf (wm-hints-icon-window hints) (decode-type window (aref vector 4)))) (when (logbitp icon-position-hint flags) (setf (wm-hints-icon-x hints) (aref vector 5) (wm-hints-icon-y hints) (aref vector 6))) (when (logbitp icon-mask-hint flags) (setf (wm-hints-icon-mask hints) (decode-type pixmap (aref vector 7)))) (when (and (logbitp window-group-hint flags) (> (length vector) 7)) (setf (wm-hints-window-group hints) (aref vector 8))) hints))) (defun encode-wm-hints (wm-hints) (declare (type wm-hints wm-hints)) (declare (values simple-vector)) (let ((input-hint #b1) (state-hint #b10) (icon-pixmap-hint #b100) (icon-window-hint #b1000) (icon-position-hint #b10000) (icon-mask-hint #b100000) (window-group-hint #b1000000) (mask #b1111111) ) (let ((vector (make-array 9 :initial-element 0)) (flags 0)) (declare (type (simple-vector 9) vector) (type card16 flags)) (when (wm-hints-input wm-hints) (setf flags input-hint (aref vector 1) (encode-type (member :off :on) (wm-hints-input wm-hints)))) (when (wm-hints-initial-state wm-hints) (setf flags (logior flags state-hint) (aref vector 2) (encode-type (member :dont-care :normal :zoom :iconic :inactive) (wm-hints-initial-state wm-hints)))) (when (wm-hints-icon-pixmap wm-hints) (setf flags (logior flags icon-pixmap-hint) (aref vector 3) (encode-type pixmap (wm-hints-icon-pixmap wm-hints)))) (when (wm-hints-icon-window wm-hints) (setf flags (logior flags icon-window-hint) (aref vector 4) (encode-type window (wm-hints-icon-window wm-hints)))) (when (and (wm-hints-icon-x wm-hints) (wm-hints-icon-y wm-hints)) (setf flags (logior flags icon-position-hint) (aref vector 5) (encode-type card16 (wm-hints-icon-x wm-hints)) (aref vector 6) (encode-type card16 (wm-hints-icon-y wm-hints)))) (when (wm-hints-icon-mask wm-hints) (setf flags (logior flags icon-mask-hint) (aref vector 7) (encode-type pixmap (wm-hints-icon-mask wm-hints)))) (when (wm-hints-window-group wm-hints) (setf flags (logior flags window-group-hint) (aref vector 8) (wm-hints-window-group wm-hints))) (setf (aref vector 0) (logior flags (logandc2 (wm-hints-flags wm-hints) mask))) vector))) (def-clx-class (wm-size-hints) (min-width nil :type (or null card16)) (min-height nil :type (or null card16)) (max-width nil :type (or null card16)) (max-height nil :type (or null card16)) (width-inc nil :type (or null card16)) (height-inc nil :type (or null card16)) (min-aspect nil :type (or null number)) (max-aspect nil :type (or null number)) (base-width nil :type (or null card16)) (base-height nil :type (or null card16)) (win-gravity nil :type (or null win-gravity)) ) (defun wm-normal-hints (window) (declare (type window window)) (declare (values wm-size-hints)) (decode-wm-size-hints (get-property window :WM_NORMAL_HINTS :type :WM_SIZE_HINTS :result-type 'vector))) (defsetf wm-normal-hints set-wm-normal-hints) (defun set-wm-normal-hints (window hints) (declare (type window window) (type wm-size-hints hints)) (declare (values wm-size-hints)) (change-property window :WM_NORMAL_HINTS (encode-wm-size-hints hints) :WM_SIZE_HINTS 32) hints) (defun wm-zoom-hints (window) (declare (type window window)) (declare (values wm-size-hints)) (decode-wm-size-hints (get-property window :WM_ZOOM_HINTS :type :WM_SIZE_HINTS :result-type 'vector))) (defsetf wm-zoom-hints set-wm-zoom-hints) (defun set-wm-zoom-hints (window hints) (declare (type window window) (type wm-size-hints hints)) (declare (values wm-size-hints)) (change-property window :WM_ZOOM_HINTS (encode-wm-size-hints hints) :WM_SIZE_HINTS 32) hints) (defun decode-wm-size-hints (vector) (declare (type (or null (simple-vector *)) vector)) (declare (values (or null wm-size-hints))) (when vector (let ((flags (aref vector 0)) (hints (make-wm-size-hints))) (declare (type card16 flags) (type wm-size-hints hints)) (setf (wm-size-hints-user-specified-position-p hints) (logbitp 0 flags)) (setf (wm-size-hints-user-specified-size-p hints) (logbitp 1 flags)) (setf (wm-size-hints-program-specified-position-p hints) (logbitp 2 flags)) (setf (wm-size-hints-program-specified-size-p hints) (logbitp 3 flags)) (when (logbitp 4 flags) (setf (wm-size-hints-min-width hints) (aref vector 5) (wm-size-hints-min-height hints) (aref vector 6))) (when (logbitp 5 flags) (setf (wm-size-hints-max-width hints) (aref vector 7) (wm-size-hints-max-height hints) (aref vector 8))) (when (logbitp 6 flags) (setf (wm-size-hints-width-inc hints) (aref vector 9) (wm-size-hints-height-inc hints) (aref vector 10))) (when (logbitp 7 flags) (setf (wm-size-hints-min-aspect hints) (/ (aref vector 11) (aref vector 12)) (wm-size-hints-max-aspect hints) (/ (aref vector 13) (aref vector 14)))) (when (> (length vector) 15) This test is for backwards compatibility since old Xlib programs can set a size - hints structure that is too small . See ICCCM . (when (logbitp 8 flags) (setf (wm-size-hints-base-width hints) (aref vector 15) (wm-size-hints-base-height hints) (aref vector 16))) (when (logbitp 9 flags) (setf (wm-size-hints-win-gravity hints) (decode-type (member-vector *win-gravity-vector*) (aref vector 17))))) (when (or (logbitp 0 flags) (logbitp 2 flags)) (setf (wm-size-hints-x hints) (aref vector 1) (wm-size-hints-y hints) (aref vector 2))) (when (or (logbitp 1 flags) (logbitp 3 flags)) (setf (wm-size-hints-width hints) (aref vector 3) (wm-size-hints-height hints) (aref vector 4))) hints))) (defun encode-wm-size-hints (hints) (declare (type wm-size-hints hints)) (declare (values simple-vector)) (let ((vector (make-array 18 :initial-element 0)) (flags 0)) (declare (type (simple-vector 18) vector) (type card16 flags)) (when (wm-size-hints-user-specified-position-p hints) (setf (ldb (byte 1 0) flags) 1)) (when (wm-size-hints-user-specified-size-p hints) (setf (ldb (byte 1 1) flags) 1)) (when (wm-size-hints-program-specified-position-p hints) (setf (ldb (byte 1 2) flags) 1)) (when (wm-size-hints-program-specified-size-p hints) (setf (ldb (byte 1 3) flags) 1)) (when (and (wm-size-hints-min-width hints) (wm-size-hints-min-height hints)) (setf (ldb (byte 1 4) flags) 1 (aref vector 5) (wm-size-hints-min-width hints) (aref vector 6) (wm-size-hints-min-height hints))) (when (and (wm-size-hints-max-width hints) (wm-size-hints-max-height hints)) (setf (ldb (byte 1 5) flags) 1 (aref vector 7) (wm-size-hints-max-width hints) (aref vector 8) (wm-size-hints-max-height hints))) (when (and (wm-size-hints-width-inc hints) (wm-size-hints-height-inc hints)) (setf (ldb (byte 1 6) flags) 1 (aref vector 9) (wm-size-hints-width-inc hints) (aref vector 10) (wm-size-hints-height-inc hints))) (let ((min-aspect (wm-size-hints-min-aspect hints)) (max-aspect (wm-size-hints-max-aspect hints))) (when (and min-aspect max-aspect) (setf (ldb (byte 1 7) flags) 1 min-aspect (rationalize min-aspect) max-aspect (rationalize max-aspect) (aref vector 11) (numerator min-aspect) (aref vector 12) (denominator min-aspect) (aref vector 13) (numerator max-aspect) (aref vector 14) (denominator max-aspect)))) (when (and (wm-size-hints-base-width hints) (wm-size-hints-base-height hints)) (setf (ldb (byte 1 8) flags) 1 (aref vector 15) (wm-size-hints-base-width hints) (aref vector 16) (wm-size-hints-base-height hints))) (when (wm-size-hints-win-gravity hints) (setf (ldb (byte 1 9) flags) 1 (aref vector 17) (encode-type (member-vector *win-gravity-vector*) (wm-size-hints-win-gravity hints)))) (when (and (wm-size-hints-x hints) (wm-size-hints-y hints)) (unless (wm-size-hints-user-specified-position-p hints) (setf (ldb (byte 1 2) flags) 1)) (setf (aref vector 1) (wm-size-hints-x hints) (aref vector 2) (wm-size-hints-y hints))) (when (and (wm-size-hints-width hints) (wm-size-hints-height hints)) (unless (wm-size-hints-user-specified-size-p hints) (setf (ldb (byte 1 3) flags) 1)) (setf (aref vector 3) (wm-size-hints-width hints) (aref vector 4) (wm-size-hints-height hints))) (setf (aref vector 0) flags) vector)) (defun icon-sizes (window) (declare (type window window)) (declare (values wm-size-hints)) (let ((vector (get-property window :WM_ICON_SIZE :type :WM_ICON_SIZE :result-type 'vector))) (declare (type (or null (simple-vector 6)) vector)) (when vector (make-wm-size-hints :min-width (aref vector 0) :min-height (aref vector 1) :max-width (aref vector 2) :max-height (aref vector 3) :width-inc (aref vector 4) :height-inc (aref vector 5))))) (defsetf icon-sizes set-icon-sizes) (defun set-icon-sizes (window wm-size-hints) (declare (type window window) (type wm-size-hints wm-size-hints)) (let ((vector (vector (wm-size-hints-min-width wm-size-hints) (wm-size-hints-min-height wm-size-hints) (wm-size-hints-max-width wm-size-hints) (wm-size-hints-max-height wm-size-hints) (wm-size-hints-width-inc wm-size-hints) (wm-size-hints-height-inc wm-size-hints)))) (change-property window :WM_ICON_SIZE vector :WM_ICON_SIZE 32) wm-size-hints)) (defun wm-protocols (window) (map 'list #'(lambda (id) (atom-name (window-display window) id)) (get-property window :WM_PROTOCOLS :type :ATOM))) (defsetf wm-protocols set-wm-protocols) (defun set-wm-protocols (window protocols) (change-property window :WM_PROTOCOLS (map 'list #'(lambda (atom) (intern-atom (window-display window) atom)) protocols) :ATOM 32) protocols) (defun wm-colormap-windows (window) (values (get-property window :WM_COLORMAP_WINDOWS :type :WINDOW :transform #'(lambda (id) (lookup-window (window-display window) id))))) (defsetf wm-colormap-windows set-wm-colormap-windows) (defun set-wm-colormap-windows (window colormap-windows) (change-property window :WM_COLORMAP_WINDOWS colormap-windows :WINDOW 32 :transform #'window-id) colormap-windows) (defun transient-for (window) (let ((prop (get-property window :WM_TRANSIENT_FOR :type :WINDOW :result-type 'list))) (and prop (lookup-window (window-display window) (car prop))))) (defsetf transient-for set-transient-for) (defun set-transient-for (window transient) (declare (type window window transient)) (change-property window :WM_TRANSIENT_FOR (list (window-id transient)) :WINDOW 32) transient) (defun set-wm-properties (window &rest options &key name icon-name resource-name resource-class command client-machine hints normal-hints zoom-hints (user-specified-position-p nil usppp) (user-specified-size-p nil usspp) (program-specified-position-p nil psppp) (program-specified-size-p nil psspp) x y width height min-width min-height max-width max-height width-inc height-inc min-aspect max-aspect base-width base-height win-gravity input initial-state icon-pixmap icon-window icon-x icon-y icon-mask window-group) (declare (arglist window &rest options &key name icon-name resource-name resource-class command client-machine hints normal-hints user-specified-position-p user-specified-size-p program-specified-position-p program-specified-size-p min-width min-height max-width max-height width-inc height-inc min-aspect max-aspect base-width base-height win-gravity input initial-state icon-pixmap icon-window icon-x icon-y icon-mask window-group)) (declare (type window window) (type (or null stringable) name icon-name resource-name resource-class client-machine) (type (or null list) command) (type (or null wm-hints) hints) (type (or null wm-size-hints) normal-hints zoom-hints) (type boolean user-specified-position-p user-specified-size-p) (type boolean program-specified-position-p program-specified-size-p) (type (or null int16) x y) (type (or null card16) width height min-width min-height max-width max-height width-inc height-inc base-width base-height) (type (or null win-gravity) win-gravity) (type (or null number) min-aspect max-aspect) (type (or null (member :off :on)) input) (type (or null (member :dont-care :normal :zoom :iconic :inactive)) initial-state) (type (or null pixmap) icon-pixmap icon-mask) (type (or null window) icon-window) (type (or null card16) icon-x icon-y) (type (or null resource-id) window-group) (dynamic-extent options)) (when name (setf (wm-name window) name)) (when icon-name (setf (wm-icon-name window) icon-name)) (when client-machine (setf (wm-client-machine window) client-machine)) (when (or resource-name resource-class) (set-wm-class window resource-name resource-class)) (when command (setf (wm-command window) command)) (if (dolist (arg '(:input :initial-state :icon-pixmap :icon-window :icon-x :icon-y :icon-mask :window-group)) (when (getf options arg) (return t))) (let ((wm-hints (if hints (copy-wm-hints hints) (make-wm-hints)))) (when input (setf (wm-hints-input wm-hints) input)) (when initial-state (setf (wm-hints-initial-state wm-hints) initial-state)) (when icon-pixmap (setf (wm-hints-icon-pixmap wm-hints) icon-pixmap)) (when icon-window (setf (wm-hints-icon-window wm-hints) icon-window)) (when icon-x (setf (wm-hints-icon-x wm-hints) icon-x)) (when icon-y (setf (wm-hints-icon-y wm-hints) icon-y)) (when icon-mask (setf (wm-hints-icon-mask wm-hints) icon-mask)) (when window-group (setf (wm-hints-input wm-hints) window-group)) (setf (wm-hints window) wm-hints)) (when hints (setf (wm-hints window) hints))) (if (dolist (arg '(:x :y :width :height :min-width :min-height :max-width :max-height :width-inc :height-inc :min-aspect :max-aspect :user-specified-position-p :user-specified-size-p :program-specified-position-p :program-specified-size-p :base-width :base-height :win-gravity)) (when (getf options arg) (return t))) (let ((size (if normal-hints (copy-wm-size-hints normal-hints) (make-wm-size-hints)))) (when x (setf (wm-size-hints-x size) x)) (when y (setf (wm-size-hints-y size) y)) (when width (setf (wm-size-hints-width size) width)) (when height (setf (wm-size-hints-height size) height)) (when min-width (setf (wm-size-hints-min-width size) min-width)) (when min-height (setf (wm-size-hints-min-height size) min-height)) (when max-width (setf (wm-size-hints-max-width size) max-width)) (when max-height (setf (wm-size-hints-max-height size) max-height)) (when width-inc (setf (wm-size-hints-width-inc size) width-inc)) (when height-inc (setf (wm-size-hints-height-inc size) height-inc)) (when min-aspect (setf (wm-size-hints-min-aspect size) min-aspect)) (when max-aspect (setf (wm-size-hints-max-aspect size) max-aspect)) (when base-width (setf (wm-size-hints-base-width size) base-width)) (when base-height (setf (wm-size-hints-base-height size) base-height)) (when win-gravity (setf (wm-size-hints-win-gravity size) win-gravity)) (when usppp (setf (wm-size-hints-user-specified-position-p size) user-specified-position-p)) (when usspp (setf (wm-size-hints-user-specified-size-p size) user-specified-size-p)) (when psppp (setf (wm-size-hints-program-specified-position-p size) program-specified-position-p)) (when psspp (setf (wm-size-hints-program-specified-size-p size) program-specified-size-p)) (setf (wm-normal-hints window) size)) (when normal-hints (setf (wm-normal-hints window) normal-hints))) (when zoom-hints (setf (wm-zoom-hints window) zoom-hints)) ) (defun set-standard-properties (window &rest options) (declare (dynamic-extent options)) (apply #'set-wm-properties window options)) (defun iconify-window (window screen) (declare (type window window) (type screen screen)) (let ((root (screen-root screen))) (declare (type window root)) (send-event root :client-message '(:substructure-redirect :substructure-notify) :window window :format 32 :type :WM_CHANGE_STATE :data (list 3)))) (defun withdraw-window (window screen) (declare (type window window) (type screen screen)) (unmap-window window) (let ((root (screen-root screen))) (declare (type window root)) (send-event root :unmap-notify '(:substructure-redirect :substructure-notify) :window window :event-window root :configure-p nil))) (def-clx-class (standard-colormap (:copier nil) (:predicate nil)) (colormap nil :type (or null colormap)) (base-pixel 0 :type pixel) (max-color nil :type (or null color)) (mult-color nil :type (or null color)) (visual nil :type (or null visual-info)) (kill nil :type (or (member nil :release-by-freeing-colormap) drawable gcontext cursor colormap font))) (defun rgb-colormaps (window property) (declare (type window window) (type (member :RGB_DEFAULT_MAP :RGB_BEST_MAP :RGB_RED_MAP :RGB_GREEN_MAP :RGB_BLUE_MAP) property)) (let ((prop (get-property window property :type :RGB_COLOR_MAP :result-type 'vector))) (declare (type (or null simple-vector) prop)) (when prop (list (make-standard-colormap :colormap (lookup-colormap (window-display window) (aref prop 0)) :base-pixel (aref prop 7) :max-color (make-color :red (card16->rgb-val (aref prop 1)) :green (card16->rgb-val (aref prop 3)) :blue (card16->rgb-val (aref prop 5))) :mult-color (make-color :red (card16->rgb-val (aref prop 2)) :green (card16->rgb-val (aref prop 4)) :blue (card16->rgb-val (aref prop 6))) :visual (and (<= 9 (length prop)) (visual-info (window-display window) (aref prop 8))) :kill (and (<= 10 (length prop)) (let ((killid (aref prop 9))) (if (= killid 1) :release-by-freeing-colormap (lookup-resource-id (window-display window) killid))))))))) (defsetf rgb-colormaps set-rgb-colormaps) (defun set-rgb-colormaps (window property maps) (declare (type window window) (type (member :RGB_DEFAULT_MAP :RGB_BEST_MAP :RGB_RED_MAP :RGB_GREEN_MAP :RGB_BLUE_MAP) property) (type list maps)) (let ((prop (make-array (* 10 (length maps)) :element-type 'card32)) (index -1)) (dolist (map maps) (setf (aref prop (incf index)) (encode-type colormap (standard-colormap-colormap map))) (setf (aref prop (incf index)) (encode-type rgb-val (color-red (standard-colormap-max-color map)))) (setf (aref prop (incf index)) (encode-type rgb-val (color-red (standard-colormap-mult-color map)))) (setf (aref prop (incf index)) (encode-type rgb-val (color-green (standard-colormap-max-color map)))) (setf (aref prop (incf index)) (encode-type rgb-val (color-green (standard-colormap-mult-color map)))) (setf (aref prop (incf index)) (encode-type rgb-val (color-blue (standard-colormap-max-color map)))) (setf (aref prop (incf index)) (encode-type rgb-val (color-blue (standard-colormap-mult-color map)))) (setf (aref prop (incf index)) (standard-colormap-base-pixel map)) (setf (aref prop (incf index)) (visual-info-id (standard-colormap-visual map))) (setf (aref prop (incf index)) (let ((kill (standard-colormap-kill map))) (etypecase kill (symbol (ecase kill ((nil) 0) ((:release-by-freeing-colormap) 1))) (drawable (drawable-id kill)) (gcontext (gcontext-id kill)) (cursor (cursor-id kill)) (colormap (colormap-id kill)) (font (font-id kill)))))) (change-property window property prop :RGB_COLOR_MAP 32))) (defun get-standard-colormap (window property) (declare (type window window) (type (member :RGB_DEFAULT_MAP :RGB_BEST_MAP :RGB_RED_MAP :RGB_GREEN_MAP :RGB_BLUE_MAP) property)) (declare (values colormap base-pixel max-color mult-color)) (let ((prop (get-property window property :type :RGB_COLOR_MAP :result-type 'vector))) (declare (type (or null simple-vector) prop)) (when prop (values (lookup-colormap (window-display window) (aref prop 0)) :green (card16->rgb-val (aref prop 3)) :blue (card16->rgb-val (aref prop 5))) :green (card16->rgb-val (aref prop 4)) :blue (card16->rgb-val (aref prop 6))))))) (defun set-standard-colormap (window property colormap base-pixel max-color mult-color) (declare (type window window) (type (member :RGB_DEFAULT_MAP :RGB_BEST_MAP :RGB_RED_MAP :RGB_GREEN_MAP :RGB_BLUE_MAP) property) (type colormap colormap) (type pixel base-pixel) (type color max-color mult-color)) (let ((prop (apply #'vector (encode-type colormap colormap) (encode-type rgb-val (color-red max-color)) (encode-type rgb-val (color-red mult-color)) (encode-type rgb-val (color-green max-color)) (encode-type rgb-val (color-green mult-color)) (encode-type rgb-val (color-blue max-color)) (encode-type rgb-val (color-blue mult-color)) base-pixel))) (change-property window property prop :RGB_COLOR_MAP 32))) (defun cut-buffer (display &key (buffer 0) (type :STRING) (result-type 'string) (transform #'card8->char) (start 0) end) Return the contents of cut - buffer BUFFER (declare (type display display) (type (integer 0 7) buffer) (type xatom type) (type array-index start) (type (or null array-index) end) (type (or null (function (integer) t)) transform)) (declare (values sequence type format bytes-after)) (let* ((root (screen-root (first (display-roots display)))) (property (aref '#(:CUT_BUFFER0 :CUT_BUFFER1 :CUT_BUFFER2 :CUT_BUFFER3 :CUT_BUFFER4 :CUT_BUFFER5 :CUT_BUFFER6 :CUT_BUFFER7) buffer))) (get-property root property :type type :result-type result-type :start start :end end :transform transform))) ( defsetf cut - buffer ( display & key ( buffer 0 ) ( type : string ) ( format 8) ( transform # ' char->card8 ) ( start 0 ) end ) ( data ) #-clx-ansi-common-lisp (define-setf-method cut-buffer (display &rest option-list) (declare (dynamic-extent option-list)) (do* ((options (copy-list option-list)) (option options (cddr option)) (store (gensym)) (dtemp (gensym)) (temps (list dtemp)) (values (list display))) ((endp option) (values (nreverse temps) (nreverse values) (list store) `(set-cut-buffer ,store ,dtemp ,@options) `(cut-buffer ,@options))) (unless (member (car option) '(:buffer :type :format :start :end :transform)) (error "Keyword arg ~s isn't recognized" (car option))) (let ((x (gensym))) (push x temps) (push (cadr option) values) (setf (cadr option) x)))) (defun #+clx-ansi-common-lisp (setf cut-buffer) #-clx-ansi-common-lisp set-cut-buffer (data display &key (buffer 0) (type :STRING) (format 8) (start 0) end (transform #'char->card8)) (declare (type sequence data) (type display display) (type (integer 0 7) buffer) (type xatom type) (type (member 8 16 32) format) (type array-index start) (type (or null array-index) end) (type (or null (function (integer) t)) transform)) (let* ((root (screen-root (first (display-roots display)))) (property (aref '#(:CUT_BUFFER0 :CUT_BUFFER1 :CUT_BUFFER2 :CUT_BUFFER3 :CUT_BUFFER4 :CUT_BUFFER5 :CUT_BUFFER6 :CUT_BUFFER7) buffer))) (change-property root property data type format :transform transform :start start :end end) data)) (defun rotate-cut-buffers (display &optional (delta 1) (careful-p t)) (declare (type display display) (type int16 delta) (type boolean careful-p)) (let* ((root (screen-root (first (display-roots display)))) (buffers '#(:cut_buffer0 :cut_buffer1 :cut_buffer2 :cut_buffer3 :cut_buffer4 :cut_buffer5 :cut_buffer6 :cut_buffer7))) (when careful-p (let ((props (list-properties root))) (dotimes (i 8) (unless (member (aref buffers i) props) (setf (cut-buffer display :buffer i) ""))))) (rotate-properties root buffers delta)))
b39f482d0370bfeae2ab96fd3b83c77e4d75091add2ae2686198604dbb4860e5
markandrus/twilio-haskell
UsageTrigger.hs
# LANGUAGE MultiParamTypeClasses # {-#LANGUAGE OverloadedStrings #-} # LANGUAGE ViewPatterns # ------------------------------------------------------------------------------- -- | -- Module : Twilio.UsageTrigger Copyright : ( C ) 2017- -- License : BSD-style (see the file LICENSE) Maintainer : < > -- Stability : provisional ------------------------------------------------------------------------------- module Twilio.UsageTrigger ( -- * Resource UsageTrigger(..) , Twilio.UsageTrigger.get ) where import Control.Monad import Control.Monad.Catch import Data.Aeson import Data.Monoid import Data.Text (Text) import Data.Time.Clock import Network.URI import Control.Monad.Twilio import Twilio.Internal.Parser import Twilio.Internal.Request import Twilio.Internal.Resource as Resource import Twilio.Types Resource data UsageTrigger = UsageTrigger { sid :: !UsageTriggerSID , dateCreated :: !UTCTime , dateUpdated :: !UTCTime , accountSID :: !AccountSID , friendlyName :: !Text , recurring :: !(Maybe Text) , usageCategory :: !Text , triggerBy :: !Text , triggerValue :: !Text , currentValue :: !Text , usageRecordURI :: !URI , callbackURL :: !(Maybe Text) , callbackMethod :: !Text , dateFired :: !(Maybe Text) , uri :: !URI } deriving (Eq, Show) instance FromJSON UsageTrigger where parseJSON (Object v) = UsageTrigger <$> v .: "sid" <*> (v .: "date_created" >>= parseDateTime) <*> (v .: "date_updated" >>= parseDateTime) <*> v .: "account_sid" <*> v .: "friendly_name" <*> v .: "recurring" <*> v .: "usage_category" <*> v .: "trigger_by" <*> v .: "trigger_value" <*> v .: "current_value" <*> (v .: "usage_record_uri" <&> parseRelativeReference >>= maybeReturn) <*> v .: "callback_url" <*> v .: "callback_method" <*> v .: "date_fired" <*> (v .: "uri" <&> parseRelativeReference >>= maybeReturn) parseJSON _ = mzero instance Get1 UsageTriggerSID UsageTrigger where get1 (getSID -> sid) = request parseJSONFromResponse =<< makeTwilioRequest ("/Usage/Triggers/" <> sid <> ".json") -- | Get a 'UsageTrigger' by 'UsageTriggerSID'. get :: MonadThrow m => UsageTriggerSID -> TwilioT m UsageTrigger get = Resource.get
null
https://raw.githubusercontent.com/markandrus/twilio-haskell/00704dc86dbf2117b855b1e2dcf8b6c0eff5bfbe/src/Twilio/UsageTrigger.hs
haskell
#LANGUAGE OverloadedStrings # ----------------------------------------------------------------------------- | Module : Twilio.UsageTrigger License : BSD-style (see the file LICENSE) Stability : provisional ----------------------------------------------------------------------------- * Resource | Get a 'UsageTrigger' by 'UsageTriggerSID'.
# LANGUAGE MultiParamTypeClasses # # LANGUAGE ViewPatterns # Copyright : ( C ) 2017- Maintainer : < > module Twilio.UsageTrigger UsageTrigger(..) , Twilio.UsageTrigger.get ) where import Control.Monad import Control.Monad.Catch import Data.Aeson import Data.Monoid import Data.Text (Text) import Data.Time.Clock import Network.URI import Control.Monad.Twilio import Twilio.Internal.Parser import Twilio.Internal.Request import Twilio.Internal.Resource as Resource import Twilio.Types Resource data UsageTrigger = UsageTrigger { sid :: !UsageTriggerSID , dateCreated :: !UTCTime , dateUpdated :: !UTCTime , accountSID :: !AccountSID , friendlyName :: !Text , recurring :: !(Maybe Text) , usageCategory :: !Text , triggerBy :: !Text , triggerValue :: !Text , currentValue :: !Text , usageRecordURI :: !URI , callbackURL :: !(Maybe Text) , callbackMethod :: !Text , dateFired :: !(Maybe Text) , uri :: !URI } deriving (Eq, Show) instance FromJSON UsageTrigger where parseJSON (Object v) = UsageTrigger <$> v .: "sid" <*> (v .: "date_created" >>= parseDateTime) <*> (v .: "date_updated" >>= parseDateTime) <*> v .: "account_sid" <*> v .: "friendly_name" <*> v .: "recurring" <*> v .: "usage_category" <*> v .: "trigger_by" <*> v .: "trigger_value" <*> v .: "current_value" <*> (v .: "usage_record_uri" <&> parseRelativeReference >>= maybeReturn) <*> v .: "callback_url" <*> v .: "callback_method" <*> v .: "date_fired" <*> (v .: "uri" <&> parseRelativeReference >>= maybeReturn) parseJSON _ = mzero instance Get1 UsageTriggerSID UsageTrigger where get1 (getSID -> sid) = request parseJSONFromResponse =<< makeTwilioRequest ("/Usage/Triggers/" <> sid <> ".json") get :: MonadThrow m => UsageTriggerSID -> TwilioT m UsageTrigger get = Resource.get
9907fd86e9a029e8c1565230024ec2fb78b1075c344cf4252593adc414514c26
rizo/streams-bench
Push_fold_k.ml
FIXME : of_list [ 1;2;3;4;5 ] | > flat_map ( fun x - > of_list [ x;x ] ) | > take 4 | > fold ( fun acc x - > x : : acc ) [ ] of_list [1;2;3;4;5] |> flat_map (fun x -> of_list [x;x]) |> take 4 |> fold (fun acc x -> x :: acc) [] *) type 'a thunk = unit -> 'a type 'a t = { run : 'r. (continue:('r -> 'r) -> 'r -> 'a -> 'r) -> 'r -> 'r } [@@unboxed] let filter p self = let run k r0 = self.run (fun ~continue r x -> continue (if p x then k ~continue r x else r)) r0 in { run } let map f self = let run k r0 = self.run (fun ~continue r x -> continue (k ~continue r (f x))) r0 in { run } let take n { run } = let run k r0 = let i = ref 1 in let k' ~continue r x = if !i = n then r else ( incr i; continue (k ~continue r x)) in run k' r0 in { run = (fun k r0 -> run k r0) } let ints : int t = let rec loop n k r = k ~continue:(fun r' -> loop (n + 1) k r') r n in { run = (fun k r -> loop 0 k r) } let singleton x = { run = (fun k r -> k ~continue:(fun r' -> r') r x) } let fold f r seq = seq.run (fun ~continue r x -> continue (f r x)) r let unfold seed next = let rec loop seed k r = match next seed with | None -> r | Some (x, seed') -> k ~continue:(fun r' -> loop seed' k r') r x in { run = (fun k r -> loop seed k r) } let rec fold_left_while f z xs = match xs with | [] -> z | x :: xs -> f ~loop:(fun s -> fold_left_while f s xs) x z let of_list list = let rec loop xs k r = match xs with | [] -> r | x :: xs' -> k ~continue:(fun r' -> loop xs' k r') r x in { run = (fun k r -> loop list k r) } let flat_map f self : 'b t = let run k r0 = self.run (fun ~continue r x -> let inner = f x in continue (inner.run k r)) r0 in { run } let ( -- ) i j = unfold i (fun x -> if x = j then None else Some (x, x + 1))
null
https://raw.githubusercontent.com/rizo/streams-bench/87baf838971c84613b801ab32b6473d397bcc23f/src/Push_fold_k.ml
ocaml
FIXME : of_list [ 1;2;3;4;5 ] | > flat_map ( fun x - > of_list [ x;x ] ) | > take 4 | > fold ( fun acc x - > x : : acc ) [ ] of_list [1;2;3;4;5] |> flat_map (fun x -> of_list [x;x]) |> take 4 |> fold (fun acc x -> x :: acc) [] *) type 'a thunk = unit -> 'a type 'a t = { run : 'r. (continue:('r -> 'r) -> 'r -> 'a -> 'r) -> 'r -> 'r } [@@unboxed] let filter p self = let run k r0 = self.run (fun ~continue r x -> continue (if p x then k ~continue r x else r)) r0 in { run } let map f self = let run k r0 = self.run (fun ~continue r x -> continue (k ~continue r (f x))) r0 in { run } let take n { run } = let run k r0 = let i = ref 1 in let k' ~continue r x = if !i = n then r else ( incr i; continue (k ~continue r x)) in run k' r0 in { run = (fun k r0 -> run k r0) } let ints : int t = let rec loop n k r = k ~continue:(fun r' -> loop (n + 1) k r') r n in { run = (fun k r -> loop 0 k r) } let singleton x = { run = (fun k r -> k ~continue:(fun r' -> r') r x) } let fold f r seq = seq.run (fun ~continue r x -> continue (f r x)) r let unfold seed next = let rec loop seed k r = match next seed with | None -> r | Some (x, seed') -> k ~continue:(fun r' -> loop seed' k r') r x in { run = (fun k r -> loop seed k r) } let rec fold_left_while f z xs = match xs with | [] -> z | x :: xs -> f ~loop:(fun s -> fold_left_while f s xs) x z let of_list list = let rec loop xs k r = match xs with | [] -> r | x :: xs' -> k ~continue:(fun r' -> loop xs' k r') r x in { run = (fun k r -> loop list k r) } let flat_map f self : 'b t = let run k r0 = self.run (fun ~continue r x -> let inner = f x in continue (inner.run k r)) r0 in { run } let ( -- ) i j = unfold i (fun x -> if x = j then None else Some (x, x + 1))
a4fc6b680adc23afaba55fa14f67103725e62b733a06ad597a9f59cfd22261db
PacktWorkshops/The-Clojure-Workshop
inflection_points.clj
In REPL : 1 . Define some sample data (def sample-data [[24.2 420031] [25.8 492657] [23.8 691995] ;min [23.2 794243] [23.1 836204] ;min [23.5 884120]]) In REPL : 2 . local - max ? and local - min ? (defn local-max? [[a b c]] (and (< (first a) (first b)) (< (first c) (first b)))) (defn local-min? [[a b c]] (and (> (first a) (first b)) (> (first c) (first b)))) ;;; In REPL: local-max? and local-min? with "clever" destructuring (defn local-max? [[[a _] [b _] [c _]]] (and (< a b) (< c b))) (defn local-min? [[[a _] [b _] [c _]]] (and (> a b) (> c b))) (local-max? (take 3 sample-data)) ;; => false (local-min? (take 3 sample-data)) ;; => false (local-min? (take 3 (drop 2 sample-data))) ;; => true ;;; In REPL (defn inflection-points [data] (lazy-seq (let [current-series (take 3 data)] (cond (< (count current-series) 3) '() (local-max? current-series) (cons (conj (second current-series) :peak) (inflection-points (rest data))) (local-min? current-series) (cons (conj (second current-series) :valley) (inflection-points (rest data))) :otherwise (inflection-points (rest data)))))) (inflection-points sample-data) = > ( [ 25.9 589014 : peak ] [ 23.8 691995 : valley ] [ 24.7 734902 : peak ] [ 23.1 836204 : valley ] ) (take 15 (inflection-points (cycle sample-data))) = > ( [ 25.9 589014 : peak ] [ 23.8 691995 : valley ] [ 24.7 734902 : peak ] [ 23.1 836204 : valley ] [ 25.9 589014 : peak ] [ 23.8 691995 : valley ] [ 24.7 734902 : peak ] [ 23.1 836204 : valley ] [ 25.9 589014 : peak ] [ 23.8 691995 : valley ] [ 24.7 734902 : peak ] [ 23.1 836204 : valley ] [ 25.9 589014 : peak ] [ 23.8 691995 : valley ] [ 24.7 734902 : peak ] )
null
https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter07/Exercise7.01/inflection_points.clj
clojure
min min In REPL: local-max? and local-min? with "clever" destructuring => false => false => true In REPL
In REPL : 1 . Define some sample data (def sample-data [[24.2 420031] [25.8 492657] [23.2 794243] [23.5 884120]]) In REPL : 2 . local - max ? and local - min ? (defn local-max? [[a b c]] (and (< (first a) (first b)) (< (first c) (first b)))) (defn local-min? [[a b c]] (and (> (first a) (first b)) (> (first c) (first b)))) (defn local-max? [[[a _] [b _] [c _]]] (and (< a b) (< c b))) (defn local-min? [[[a _] [b _] [c _]]] (and (> a b) (> c b))) (local-max? (take 3 sample-data)) (local-min? (take 3 sample-data)) (local-min? (take 3 (drop 2 sample-data))) (defn inflection-points [data] (lazy-seq (let [current-series (take 3 data)] (cond (< (count current-series) 3) '() (local-max? current-series) (cons (conj (second current-series) :peak) (inflection-points (rest data))) (local-min? current-series) (cons (conj (second current-series) :valley) (inflection-points (rest data))) :otherwise (inflection-points (rest data)))))) (inflection-points sample-data) = > ( [ 25.9 589014 : peak ] [ 23.8 691995 : valley ] [ 24.7 734902 : peak ] [ 23.1 836204 : valley ] ) (take 15 (inflection-points (cycle sample-data))) = > ( [ 25.9 589014 : peak ] [ 23.8 691995 : valley ] [ 24.7 734902 : peak ] [ 23.1 836204 : valley ] [ 25.9 589014 : peak ] [ 23.8 691995 : valley ] [ 24.7 734902 : peak ] [ 23.1 836204 : valley ] [ 25.9 589014 : peak ] [ 23.8 691995 : valley ] [ 24.7 734902 : peak ] [ 23.1 836204 : valley ] [ 25.9 589014 : peak ] [ 23.8 691995 : valley ] [ 24.7 734902 : peak ] )
79508182d5562dcb160b55a0a28a118c776b187c96e130df8d09d1c007474a82
xapi-project/squeezed
squeeze_xen.ml
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc. * * 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 ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 . * Copyright (C) 2006-2009 Citrix Systems Inc. * * 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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. *) * Aims are : 1 . make this code robust to domains being created and destroyed around it . 2 . not depend on any other info beyond domain_getinfolist and . 1. make this code robust to domains being created and destroyed around it. 2. not depend on any other info beyond domain_getinfolist and xenstore. *) * Interface between the abstract domain memory balancing code and Xen . open Xcp_service open Squeezed_xenstore open Xapi_stdext_threads.Threadext module M = Debug.Make (struct let name = "memory" end) let debug = Squeeze.debug let error = Squeeze.error let _domain_type = "/domain-type" (* immutable *) let _initial_reservation = "/memory/initial-reservation" (* immutable *) let _target = "/memory/target" (* immutable *) let _feature_balloon = "/control/feature-balloon" (* immutable *) let _data_updated = "/data/updated" (* mutable: written by guest agent *) let _memory_offset = "/memory/memory-offset" (* immutable *) let _uncooperative = "/memory/uncooperative" (* mutable: written by us *) let _dynamic_min = "/memory/dynamic-min" (* mutable: written by domain manager *) let _dynamic_max = "/memory/dynamic-max" (* mutable: written by domain manager *) let ( ** ) = Int64.mul let ( +* ) = Int64.add let ( -* ) = Int64.sub let mib = 1024L let set_difference a b = List.filter (fun x -> not (List.mem x b)) a * Same as xen commandline let low_mem_emergency_pool = 1L ** mib * Return the extra amount we always add onto maxmem let xen_max_offset_kib domain_type = let maxmem_mib = match domain_type with | `hvm -> Memory.HVM.xen_max_offset_mib | `pv_in_pvh -> Memory.PVinPVH.xen_max_offset_mib | `pv -> Memory.Linux.xen_max_offset_mib in Memory.kib_of_mib maxmem_mib (** Cache of per-domain info, to avoid repeated per-domain queries *) module Domain = struct type per_domain = { path: string ; domain_type: [`hvm | `pv_in_pvh | `pv] ; mutable maxmem: int64 ; keys: (string, string option) Hashtbl.t } type t = (int, per_domain) Hashtbl.t let cache = Hashtbl.create 10 let m = Mutex.create () let get_domain_type path di = try match Client.immediate (get_client ()) (fun xs -> Client.read xs (path ^ _domain_type)) with | "hvm" -> `hvm | "pv" -> `pv | "pv-in-pvh" -> `pv_in_pvh | _ -> failwith "undefined domain_type" with _ -> Fallback for the upgrade case , where the new xs key may not exist if di.Xenctrl.hvm_guest then `hvm else `pv let maxmem_of_dominfo di domain_type = let memory_max_kib = Xenctrl.pages_to_kib (Int64.of_nativeint di.Xenctrl.max_memory_pages) in (* Misc other stuff appears in max_memory_pages *) max 0L (memory_max_kib -* xen_max_offset_kib domain_type) (* get_per_domain can return None if the domain is deleted by someone else while we are processing some other event handlers *) let get_per_domain xc domid = if Hashtbl.mem cache domid then Some (Hashtbl.find cache domid) else try let path = Printf.sprintf "/local/domain/%d" domid in let di = Xenctrl.domain_getinfo xc domid in let domain_type = get_domain_type path di in let d = { path ; domain_type ; maxmem= maxmem_of_dominfo di domain_type ; keys= Hashtbl.create 10 } in Hashtbl.replace cache domid d ; Some d with Xenctrl.Error _ -> Hashtbl.remove cache domid ; None let remove_gone_domains_cache xc = let current_domains = Xenctrl.domain_getinfolist xc 0 in Mutex.execute m (fun () -> let alive_domids = List.map (fun d -> d.Xenctrl.domid) current_domains in let known_domids = Hashtbl.fold (fun k _ acc -> k :: acc) cache [] in let gone_domids = set_difference known_domids alive_domids in List.iter (fun d -> debug "Remove domid %d in cache" d ; Hashtbl.remove cache d) gone_domids) let _introduceDomain = "@introduceDomain" let _releaseDomain = "@releaseDomain" exception Watch_overflow let watch_xenstore () = Xenctrl.with_intf (fun xc -> let interesting_paths = [ ["memory"; "initial-reservation"] ; ["memory"; "target"] ; ["control"; "feature-balloon"] ; ["data"; "updated"] ; ["memory"; "memory-offset"] ; ["memory"; "uncooperative"] ; ["memory"; "dynamic-min"] ; ["memory"; "dynamic-max"] ] in let watches domid = List.map (fun p -> Printf.sprintf "/local/domain/%d/%s" domid (String.concat "/" p)) interesting_paths in let module IntSet = Set.Make (struct type t = int let compare = compare end) in let watching_domids = ref IntSet.empty in let watch_token domid = Printf.sprintf "squeezed:domain-%d" domid in let look_for_different_domains () = let list_domains xc = let dis = Xenctrl.domain_getinfolist xc 0 in List.fold_left (fun set x -> if not x.Xenctrl.shutdown then IntSet.add x.Xenctrl.domid set else set) IntSet.empty dis in let existing = list_domains xc in let arrived = IntSet.diff existing !watching_domids in IntSet.iter (fun domid -> debug "Adding watches for domid: %d" domid ; List.iter (fun x -> try Client.immediate (get_client ()) (fun xs -> Client.watch xs x (watch_token domid)) with e -> error "watch path=%s token=%s: %s" x (watch_token domid) (Printexc.to_string e)) (watches domid)) arrived ; let gone = IntSet.diff !watching_domids existing in IntSet.iter (fun domid -> debug "Removing watches for domid: %d" domid ; List.iter (fun x -> try Client.immediate (get_client ()) (fun xs -> Client.unwatch xs x (watch_token domid)) with e -> error "unwatch path=%s token=%s: %s" x (watch_token domid) (Printexc.to_string e)) (watches domid)) gone ; watching_domids := existing ; Mutex.execute m (fun () -> IntSet.iter (Hashtbl.remove cache) gone ; IntSet.iter (fun domid -> try ignore (get_per_domain xc domid) with _ -> ()) arrived) in (* Watches are generated by concurrent activity on the system. We must decide whether to let them queue up in xenstored, or here. Since xenstored is more important for system reliability, we choose to drain its queue as quickly as possible and put the queue here. If this queue gets too large we should throw it away, disconnect and reconnect. *) let incoming_watches = Queue.create () in let queue_overflowed = ref false in let incoming_watches_m = Mutex.create () in let incoming_watches_c = Condition.create () in let enqueue_watches event = Mutex.execute incoming_watches_m (fun () -> if Queue.length incoming_watches = 1024 then queue_overflowed := true else Queue.push event incoming_watches ; Condition.signal incoming_watches_c) in let dequeue_watches callback = try while true do let event = Mutex.execute incoming_watches_m (fun () -> while Queue.is_empty incoming_watches && not !queue_overflowed do Condition.wait incoming_watches_c incoming_watches_m done ; if !queue_overflowed then ( error "xenstore watch event queue overflow: this suggests \ the processing thread deadlocked somehow." ; raise Watch_overflow ) ; Queue.pop incoming_watches) in let () = callback event in () done with Watch_overflow -> () in let process_one_watch xc xs (path, token) = if path = _introduceDomain || path = _releaseDomain then look_for_different_domains () else match Astring.String.cuts ~empty:false ~sep:"/" path with | "local" :: "domain" :: domid :: rest when List.mem rest interesting_paths -> let value = try Some (Client.read xs path) with _ -> None in let domid = int_of_string domid in Mutex.execute m (fun () -> match get_per_domain xc domid with | None -> () | Some per_domain -> let key = "/" ^ String.concat "/" rest in debug "watch %s <- %s" key (Option.value ~default:"None" value) ; Hashtbl.replace per_domain.keys key value) | _ -> debug "Ignoring unexpected watch: %s" path in let register_for_watches xc = Client.immediate (get_client ()) (fun xs -> Client.set_watch_callback (get_client ()) enqueue_watches ; Client.watch xs _introduceDomain "squeezed" ; Client.watch xs _releaseDomain "squeezed" ; dequeue_watches (process_one_watch xc xs)) in while true do Xapi_stdext_pervasives.Pervasiveext.finally (fun () -> debug "(re)starting xenstore watch thread" ; Xenctrl.with_intf register_for_watches) (fun () -> Thread.delay 5.) done) let start_watch_xenstore_thread () = let (_ : Thread.t) = Thread.create (fun () -> while true do try watch_xenstore () with e -> error "watch_xenstore: %s" (Printexc.to_string e) ; Thread.delay 1. done) () in () let get_domain_type cnx domid = Mutex.execute m (fun () -> Option.fold ~none:`pv ~some:(fun d -> d.domain_type) (get_per_domain cnx domid)) let get_maxmem cnx domid = Mutex.execute m (fun () -> Option.fold ~none:0L ~some:(fun d -> d.maxmem) (get_per_domain cnx domid)) let set_maxmem_noexn xc domid mem = Mutex.execute m (fun () -> match get_per_domain xc domid with | None -> () | Some per_domain -> if per_domain.maxmem <> mem then ( debug "Xenctrl.domain_setmaxmem domid=%d max=%Ld (was=%Ld)" domid mem per_domain.maxmem ; try Xenctrl.domain_setmaxmem xc domid mem ; per_domain.maxmem <- mem with e -> error "Xenctrl.domain_setmaxmem domid=%d max=%Ld: (was=%Ld) %s" domid mem per_domain.maxmem (Printexc.to_string e) )) (** Read a particular domain's key, using the cache *) let read xc domid key = let x = Mutex.execute m (fun () -> match get_per_domain xc domid with | None -> None | Some per_domain -> if Hashtbl.mem per_domain.keys key then Hashtbl.find per_domain.keys key else let x = try Some (Client.immediate (get_client ()) (fun xs -> Client.read xs (per_domain.path ^ key))) with Xs_protocol.Enoent _ -> None in Hashtbl.replace per_domain.keys key x ; x) in match x with Some y -> y | None -> raise (Xs_protocol.Enoent key) * Write a new ( key , value ) pair into a domain 's directory in xenstore . Do n't write anything if the domain 's directory does n't exist . Do n't throw exceptions . write anything if the domain's directory doesn't exist. Don't throw exceptions. *) let write_noexn xc domid key value = match get_per_domain xc domid with | None -> () | Some per_domain -> ( if (not (Hashtbl.mem per_domain.keys key)) || Hashtbl.find per_domain.keys key <> Some value then try Client.transaction (get_client ()) (fun t -> (* Fail if the directory has been deleted *) ignore (Client.read t per_domain.path) ; Client.write t (per_domain.path ^ key) value) ; Hashtbl.replace per_domain.keys key (Some value) with e -> (* Log but don't throw an exception *) error "xenstore-write %d %s = %s failed: %s" domid key value (Printexc.to_string e) ) (** Returns true if the key exists, false otherwise *) let exists xc domid key = try ignore (read xc domid key) ; true with Xs_protocol.Enoent _ -> false (** Delete the key. Don't throw exceptions. *) let rm_noexn xc domid key = match get_per_domain xc domid with | None -> () | Some per_domain -> ( Hashtbl.replace per_domain.keys key None ; try Client.immediate (get_client ()) (fun xs -> Client.rm xs (per_domain.path ^ key)) with e -> error "xenstore-rm %d %s: %s" domid key (Printexc.to_string e) ) (** {High-level functions} *) (** Set a domain's memory target. Don't throw an exception if the domain has been destroyed. *) let set_target_noexn cnx domid target_kib = write_noexn cnx domid _target (Int64.to_string target_kib) * Get a domain 's memory target . Throws Xenbus . Xb . Noent if the domain has been destroyed been destroyed *) let get_target cnx domid = Int64.of_string (read cnx domid _target) * a domain as uncooperative . Do n't throw an exception if the domain has been destroyed . been destroyed. *) let set_uncooperative_noexn cnx domid x = if x then write_noexn cnx domid _uncooperative "" else rm_noexn cnx domid _uncooperative * Query a domain 's uncooperative status . Throws Xenbus . Xb . Noent if the domain has been destroyed domain has been destroyed *) let get_uncooperative_noexn cnx domid = exists cnx domid _uncooperative (** Set a domain's memory-offset. Don't throw an exception if the domain has been destroyed *) let set_memory_offset_noexn cnx domid offset_kib = write_noexn cnx domid _memory_offset (Int64.to_string offset_kib) (** Query a domain's memory-offset. Throws Xs_protocol.Enoent _ if the domain has been destroyed *) let get_memory_offset cnx domid = Int64.of_string (read cnx domid _memory_offset) (** Set a domain's maxmem. Don't throw an exception if the domain has been destroyed *) let set_maxmem_noexn cnx domid target_kib = let offset_kib : int64 = try get_memory_offset cnx domid with _ -> 0L in let maxmem_kib = xen_max_offset_kib (get_domain_type cnx domid) +* target_kib +* offset_kib in set_maxmem_noexn cnx domid maxmem_kib (** Return true if feature_balloon has been advertised *) let get_feature_balloon cnx domid = try ignore (read cnx domid _feature_balloon) ; true with Xs_protocol.Enoent _ -> false (** Return true if the guest agent has been advertised *) let get_guest_agent cnx domid = try ignore (read cnx domid _data_updated) ; true with Xs_protocol.Enoent _ -> false (** Query a domain's initial reservation. Throws Xs_protocol.Enoent _ if the domain has been destroyed *) let get_initial_reservation cnx domid = Int64.of_string (read cnx domid _initial_reservation) (** Query a domain's dynamic_min. Throws Xs_protocol.Enoent _ if the domain has been destroyed *) let get_dynamic_min cnx domid = Int64.of_string (read cnx domid _dynamic_min) (** Query a domain's dynamic_max. Throws Xs_protocol.Enoent _ if the domain has been destroyed *) let get_dynamic_max cnx domid = Int64.of_string (read cnx domid _dynamic_max) end (** Record when the domain was last co-operative *) let when_domain_was_last_cooperative : (int, float) Hashtbl.t = Hashtbl.create 10 let update_cooperative_table host = let now = Unix.gettimeofday () in let alive_domids = List.map (fun d -> d.Squeeze.domid) host.Squeeze.domains in let known_domids = Hashtbl.fold (fun k _ acc -> k :: acc) when_domain_was_last_cooperative [] in let gone_domids = set_difference known_domids alive_domids in List.iter (Hashtbl.remove when_domain_was_last_cooperative) gone_domids ; let arrived_domids = set_difference alive_domids known_domids in (* Assume domains are initially co-operative *) List.iter (fun x -> Hashtbl.replace when_domain_was_last_cooperative x now) arrived_domids ; (* Main business: mark any domain which is on or above target OR which cannot balloon as co-operative *) List.iter (fun d -> if (not d.Squeeze.can_balloon) || Squeeze.has_hit_target d.Squeeze.inaccuracy_kib d.Squeeze.memory_actual_kib d.Squeeze.target_kib then Hashtbl.replace when_domain_was_last_cooperative d.Squeeze.domid now) host.Squeeze.domains * Update all the flags in xenstore let update_cooperative_flags cnx = let now = Unix.gettimeofday () in Hashtbl.iter (fun domid last_time -> let old_value = Domain.get_uncooperative_noexn cnx domid in let new_value = now -. last_time > 20. in if old_value <> new_value then Domain.set_uncooperative_noexn cnx domid new_value) when_domain_was_last_cooperative (** Best-effort creation of a 'host' structure and a simple debug line showing its derivation *) let make_host ~verbose ~xc = (* Wait for any scrubbing so that we don't end up with no immediately usable pages -- this might cause something else to fail (eg domain builder?) *) while Int64.div ((Xenctrl.physinfo xc).Xenctrl.scrub_pages |> Int64.of_nativeint) 1024L <> 0L do ignore (Unix.select [] [] [] 0.25) done ; Some VMs are considered by us ( but not by xen ) to have an " initial - reservation " . For VMs which have never run ( eg which are still being built or restored ) we take the difference between memory_actual_kib and the reservation and subtract this manually from the host 's free memory . Note that we do n't get an atomic snapshot of system state so there is a natural race between the hypercalls . Hopefully the memory is being consumed fairly slowly and so the error is small . "initial-reservation". For VMs which have never run (eg which are still being built or restored) we take the difference between memory_actual_kib and the reservation and subtract this manually from the host's free memory. Note that we don't get an atomic snapshot of system state so there is a natural race between the hypercalls. Hopefully the memory is being consumed fairly slowly and so the error is small. *) Additionally we have the concept of a ' reservation ' separate from a domain which allows us to postpone domain creates until such time as there is lots of memory available . This minimises the chance that the remaining free memory will be too fragmented to actually use ( some xen structures require contiguous frames ) which allows us to postpone domain creates until such time as there is lots of memory available. This minimises the chance that the remaining free memory will be too fragmented to actually use (some xen structures require contiguous frames) *) let reserved_kib = ref 0L in (* We cannot query simultaneously the host memory info and the domain memory info. Furthermore the call to domain_getinfolist is not atomic but comprised of many hypercall invocations. *) let domain_infolist = Xenctrl.domain_getinfolist xc 0 in (* Check if we are managing dom0 *) let domain_infolist = if !Squeeze.manage_domain_zero then domain_infolist else List.filter (fun di -> di.Xenctrl.domid > 0) domain_infolist in let cnx = xc in let domains = List.concat (List.map (fun di -> try let domain_type = Domain.get_domain_type cnx di.Xenctrl.domid in let memory_actual_kib = Xenctrl.pages_to_kib (Int64.of_nativeint di.Xenctrl.total_memory_pages) in let memory_shadow_kib = match domain_type with | `hvm | `pv_in_pvh -> ( try Memory.kib_of_mib (Int64.of_int (Xenctrl.shadow_allocation_get xc di.Xenctrl.domid)) with _ -> 0L ) | `pv -> 0L in (* dom0 is special for some reason *) let memory_max_kib = if di.Xenctrl.domid = 0 then 0L else Domain.maxmem_of_dominfo di domain_type in let can_balloon = Domain.get_feature_balloon cnx di.Xenctrl.domid in let has_guest_agent = Domain.get_guest_agent cnx di.Xenctrl.domid in let has_booted = can_balloon || has_guest_agent in Once the domain tells us it has booted , we assume it 's not currently ballooning and record the offset between memory_actual and target . We assume this is constant over the lifetime of the domain . currently ballooning and record the offset between memory_actual and target. We assume this is constant over the lifetime of the domain. *) let offset_kib : int64 = if not has_booted then 0L else try Domain.get_memory_offset cnx di.Xenctrl.domid with Xs_protocol.Enoent _ -> Our memory_actual_kib value was sampled before reading which means there is a slight race . The race is probably only noticable in the hypercall simulator . However we can fix it by resampling memory_actual * after * noticing the feature - balloon flag . xenstore which means there is a slight race. The race is probably only noticable in the hypercall simulator. However we can fix it by resampling memory_actual *after* noticing the feature-balloon flag. *) let target_kib = Domain.get_target cnx di.Xenctrl.domid in let memory_actual_kib' = Xenctrl.pages_to_kib (Int64.of_nativeint (Xenctrl.domain_getinfo xc di.Xenctrl.domid) .Xenctrl.total_memory_pages) in let offset_kib = memory_actual_kib' -* target_kib in debug "domid %d just %s; calibrating memory-offset = %Ld KiB" di.Xenctrl.domid ( match (can_balloon, has_guest_agent) with | true, false -> "advertised a balloon driver" | true, true -> "started a guest agent and advertised a balloon driver" | false, true -> "started a guest agent (but has no balloon driver)" | false, false -> "N/A" (*impossible: see if has_booted above *) ) offset_kib ; Domain.set_memory_offset_noexn cnx di.Xenctrl.domid offset_kib ; offset_kib in let memory_actual_kib = memory_actual_kib -* offset_kib in let domain = { Squeeze.domid= di.Xenctrl.domid ; can_balloon ; dynamic_min_kib= 0L ; dynamic_max_kib= 0L ; target_kib= 0L ; memory_actual_kib= 0L ; memory_max_kib ; inaccuracy_kib= 4L } in (* If the domain has never run (detected by being paused, not shutdown and clocked up no CPU time) then we'll need to consider the domain's "initial-reservation". Note that the other fields won't necessarily have been created yet. *) (* If the domain has yet to boot properly then we assume it is using at least its "initial-reservation". *) if not has_booted then ( let initial_reservation_kib = Domain.get_initial_reservation cnx di.Xenctrl.domid in let unaccounted_kib = max 0L (initial_reservation_kib -* memory_actual_kib -* memory_shadow_kib ) in reserved_kib := Int64.add !reserved_kib unaccounted_kib ; [ { domain with Squeeze.dynamic_min_kib= memory_max_kib ; dynamic_max_kib= memory_max_kib ; target_kib= memory_max_kib ; memory_actual_kib= memory_max_kib } ] ) else let target_kib = Domain.get_target cnx di.Xenctrl.domid in min and are written separately ; if we notice they (* are missing set them both to the target for now. *) let min_kib, max_kib = try ( Domain.get_dynamic_min cnx di.Xenctrl.domid , Domain.get_dynamic_max cnx di.Xenctrl.domid ) with _ -> (target_kib, target_kib) in [ { domain with Squeeze.dynamic_min_kib= min_kib ; dynamic_max_kib= max_kib ; target_kib ; memory_actual_kib } ] with | Xs_protocol.Enoent _ -> useful debug message is printed by the * functions [] | e -> if verbose then debug "Skipping domid %d: %s" di.Xenctrl.domid (Printexc.to_string e) ; []) domain_infolist) in (* For the host free memory we sum the free pages and the pages needing scrubbing: we don't want to adjust targets simply because the scrubber is slow. *) let physinfo = Xenctrl.physinfo xc in let free_pages_kib = Xenctrl.pages_to_kib (Int64.of_nativeint physinfo.Xenctrl.free_pages) and scrub_pages_kib = Xenctrl.pages_to_kib (Int64.of_nativeint physinfo.Xenctrl.scrub_pages) and total_pages_kib = Xenctrl.pages_to_kib (Int64.of_nativeint physinfo.Xenctrl.total_pages) in let free_mem_kib = free_pages_kib +* scrub_pages_kib in (* Sum up the 'reservations' which exist separately from domains *) let non_domain_reservations = Squeezed_state.total_reservations Squeezed_state._service domain_infolist in if verbose && non_domain_reservations <> 0L then debug "Total non-domain reservations = %Ld" non_domain_reservations ; reserved_kib := Int64.add !reserved_kib non_domain_reservations ; let host = Squeeze.make_host ~domains ~free_mem_kib:(Int64.sub free_mem_kib !reserved_kib) in (* Externally-visible side-effects. It's a bit ugly to include these here: *) update_cooperative_table host ; update_cooperative_flags cnx ; Domain.remove_gone_domains_cache xc ; (* It's always safe to _decrease_ a domain's maxmem towards target. This catches the case where a toolstack creates a domain with maxmem = static_max and target < static_max (eg CA-36316) *) let updates = Squeeze.IntMap.fold (fun domid domain updates -> if domain.Squeeze.target_kib < Domain.get_maxmem xc domid then Squeeze.IntMap.add domid domain.Squeeze.target_kib updates else updates) host.Squeeze.domid_to_domain Squeeze.IntMap.empty in Squeeze.IntMap.iter (Domain.set_maxmem_noexn xc) updates ; ( Printf.sprintf "F%Ld S%Ld R%Ld T%Ld" free_pages_kib scrub_pages_kib !reserved_kib total_pages_kib , host ) (** Best-effort update of a domain's memory target. *) let execute_action ~xc action = try let domid = action.Squeeze.action_domid in let target_kib = action.Squeeze.new_target_kib in if target_kib < 0L then failwith (Printf.sprintf "Proposed target is negative (domid %d): %Ld" domid target_kib) ; let cnx = xc in let memory_max_kib = Domain.get_maxmem cnx domid in (* We only set the target of a domain if it has exposed feature-balloon: otherwise we can screw up the memory-offset calculations for partially-built domains. *) let can_balloon = Domain.get_feature_balloon cnx domid in if target_kib > memory_max_kib then ( Domain.set_maxmem_noexn cnx domid target_kib ; if can_balloon then Domain.set_target_noexn cnx domid target_kib else debug "Not setting target for domid: %d since no feature-balloon. Setting \ maxmem to %Ld" domid target_kib ) else ( if can_balloon then Domain.set_target_noexn cnx domid target_kib else debug "Not setting target for domid: %d since no feature-balloon. Setting \ maxmem to %Ld" domid target_kib ; Domain.set_maxmem_noexn cnx domid target_kib ) with e -> debug "Failed to reset balloon target (domid: %d) (target: %Ld): %s" action.Squeeze.action_domid action.Squeeze.new_target_kib (Printexc.to_string e) (** Domain.creates take "ordinary" memory as well as "special" memory *) let extra_mem_to_keep = 8L ** mib let target_host_free_mem_kib = low_mem_emergency_pool +* extra_mem_to_keep (** No need to be too exact *) let free_memory_tolerance_kib = 512L let io ~xc ~verbose = { verbose ; Squeeze.gettimeofday= Unix.gettimeofday ; make_host= (fun () -> make_host ~verbose ~xc) ; domain_setmaxmem= (fun domid kib -> execute_action ~xc {Squeeze.action_domid= domid; new_target_kib= kib}) ; wait= (fun delay -> ignore (Unix.select [] [] [] delay)) ; execute_action= (fun action -> execute_action ~xc action) ; target_host_free_mem_kib ; free_memory_tolerance_kib } let change_host_free_memory ~xc required_mem_kib success_condition = Squeeze.change_host_free_memory (io ~verbose:true ~xc) required_mem_kib success_condition let free_memory ~xc required_mem_kib = let io = io ~verbose:true ~xc in Squeeze.change_host_free_memory io (required_mem_kib +* io.Squeeze.target_host_free_mem_kib) (fun x -> x >= required_mem_kib +* io.Squeeze.target_host_free_mem_kib) let free_memory_range ~xc min_kib max_kib = let io = io ~verbose:true ~xc in Squeeze.free_memory_range io min_kib max_kib let is_balanced x = Int64.sub x target_host_free_mem_kib < free_memory_tolerance_kib let balance_memory ~xc = Squeeze.balance_memory (io ~verbose:true ~xc) (** Return true if the host memory is currently unbalanced and needs rebalancing *) let is_host_memory_unbalanced ~xc = Squeeze.is_host_memory_unbalanced (io ~verbose:false ~xc) If we want to manage domain 0 , we must write the policy settings to let configure_domain_zero () = (* Domain.write_noexn will drop the write if the directory doesn't exist we make sure it already exists. *) Client.immediate (get_client ()) (fun xs -> Client.mkdir xs "/local/domain/0") ; Xenctrl.with_intf (fun xc -> Domain.write_noexn xc 0 _dynamic_min (Int64.to_string (Memory.kib_of_bytes_used !Squeeze.domain_zero_dynamic_min)) ; let dynamic_max = match !Squeeze.domain_zero_dynamic_max with | Some x -> Memory.kib_of_bytes_used x | None -> If this is the first time we 've started after boot then we can use the current domain 0 total_pages value . Otherwise we continue to use the version already in xenstore . use the current domain 0 total_pages value. Otherwise we continue to use the version already in xenstore. *) if Domain.exists xc 0 _dynamic_max then Int64.of_string (Domain.read xc 0 _dynamic_max) else let di = Xenctrl.domain_getinfo xc 0 in Xenctrl.pages_to_kib (Int64.of_nativeint di.Xenctrl.total_memory_pages) in Domain.write_noexn xc 0 _dynamic_max (Int64.to_string dynamic_max) ; if not (Domain.exists xc 0 _target) then Domain.write_noexn xc 0 _target (Int64.to_string dynamic_max) ; Domain.write_noexn xc 0 _feature_balloon "1")
null
https://raw.githubusercontent.com/xapi-project/squeezed/1c23bfe2d8284384ad66fa0dedb1583b570369b8/src/squeeze_xen.ml
ocaml
immutable immutable immutable immutable mutable: written by guest agent immutable mutable: written by us mutable: written by domain manager mutable: written by domain manager * Cache of per-domain info, to avoid repeated per-domain queries Misc other stuff appears in max_memory_pages get_per_domain can return None if the domain is deleted by someone else while we are processing some other event handlers Watches are generated by concurrent activity on the system. We must decide whether to let them queue up in xenstored, or here. Since xenstored is more important for system reliability, we choose to drain its queue as quickly as possible and put the queue here. If this queue gets too large we should throw it away, disconnect and reconnect. * Read a particular domain's key, using the cache Fail if the directory has been deleted Log but don't throw an exception * Returns true if the key exists, false otherwise * Delete the key. Don't throw exceptions. * {High-level functions} * Set a domain's memory target. Don't throw an exception if the domain has been destroyed. * Set a domain's memory-offset. Don't throw an exception if the domain has been destroyed * Query a domain's memory-offset. Throws Xs_protocol.Enoent _ if the domain has been destroyed * Set a domain's maxmem. Don't throw an exception if the domain has been destroyed * Return true if feature_balloon has been advertised * Return true if the guest agent has been advertised * Query a domain's initial reservation. Throws Xs_protocol.Enoent _ if the domain has been destroyed * Query a domain's dynamic_min. Throws Xs_protocol.Enoent _ if the domain has been destroyed * Query a domain's dynamic_max. Throws Xs_protocol.Enoent _ if the domain has been destroyed * Record when the domain was last co-operative Assume domains are initially co-operative Main business: mark any domain which is on or above target OR which cannot balloon as co-operative * Best-effort creation of a 'host' structure and a simple debug line showing its derivation Wait for any scrubbing so that we don't end up with no immediately usable pages -- this might cause something else to fail (eg domain builder?) We cannot query simultaneously the host memory info and the domain memory info. Furthermore the call to domain_getinfolist is not atomic but comprised of many hypercall invocations. Check if we are managing dom0 dom0 is special for some reason impossible: see if has_booted above If the domain has never run (detected by being paused, not shutdown and clocked up no CPU time) then we'll need to consider the domain's "initial-reservation". Note that the other fields won't necessarily have been created yet. If the domain has yet to boot properly then we assume it is using at least its "initial-reservation". are missing set them both to the target for now. For the host free memory we sum the free pages and the pages needing scrubbing: we don't want to adjust targets simply because the scrubber is slow. Sum up the 'reservations' which exist separately from domains Externally-visible side-effects. It's a bit ugly to include these here: It's always safe to _decrease_ a domain's maxmem towards target. This catches the case where a toolstack creates a domain with maxmem = static_max and target < static_max (eg CA-36316) * Best-effort update of a domain's memory target. We only set the target of a domain if it has exposed feature-balloon: otherwise we can screw up the memory-offset calculations for partially-built domains. * Domain.creates take "ordinary" memory as well as "special" memory * No need to be too exact * Return true if the host memory is currently unbalanced and needs rebalancing Domain.write_noexn will drop the write if the directory doesn't exist we make sure it already exists.
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc. * * 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 ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 . * Copyright (C) 2006-2009 Citrix Systems Inc. * * 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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. *) * Aims are : 1 . make this code robust to domains being created and destroyed around it . 2 . not depend on any other info beyond domain_getinfolist and . 1. make this code robust to domains being created and destroyed around it. 2. not depend on any other info beyond domain_getinfolist and xenstore. *) * Interface between the abstract domain memory balancing code and Xen . open Xcp_service open Squeezed_xenstore open Xapi_stdext_threads.Threadext module M = Debug.Make (struct let name = "memory" end) let debug = Squeeze.debug let error = Squeeze.error let _dynamic_min = "/memory/dynamic-min" let _dynamic_max = "/memory/dynamic-max" let ( ** ) = Int64.mul let ( +* ) = Int64.add let ( -* ) = Int64.sub let mib = 1024L let set_difference a b = List.filter (fun x -> not (List.mem x b)) a * Same as xen commandline let low_mem_emergency_pool = 1L ** mib * Return the extra amount we always add onto maxmem let xen_max_offset_kib domain_type = let maxmem_mib = match domain_type with | `hvm -> Memory.HVM.xen_max_offset_mib | `pv_in_pvh -> Memory.PVinPVH.xen_max_offset_mib | `pv -> Memory.Linux.xen_max_offset_mib in Memory.kib_of_mib maxmem_mib module Domain = struct type per_domain = { path: string ; domain_type: [`hvm | `pv_in_pvh | `pv] ; mutable maxmem: int64 ; keys: (string, string option) Hashtbl.t } type t = (int, per_domain) Hashtbl.t let cache = Hashtbl.create 10 let m = Mutex.create () let get_domain_type path di = try match Client.immediate (get_client ()) (fun xs -> Client.read xs (path ^ _domain_type)) with | "hvm" -> `hvm | "pv" -> `pv | "pv-in-pvh" -> `pv_in_pvh | _ -> failwith "undefined domain_type" with _ -> Fallback for the upgrade case , where the new xs key may not exist if di.Xenctrl.hvm_guest then `hvm else `pv let maxmem_of_dominfo di domain_type = let memory_max_kib = Xenctrl.pages_to_kib (Int64.of_nativeint di.Xenctrl.max_memory_pages) in max 0L (memory_max_kib -* xen_max_offset_kib domain_type) let get_per_domain xc domid = if Hashtbl.mem cache domid then Some (Hashtbl.find cache domid) else try let path = Printf.sprintf "/local/domain/%d" domid in let di = Xenctrl.domain_getinfo xc domid in let domain_type = get_domain_type path di in let d = { path ; domain_type ; maxmem= maxmem_of_dominfo di domain_type ; keys= Hashtbl.create 10 } in Hashtbl.replace cache domid d ; Some d with Xenctrl.Error _ -> Hashtbl.remove cache domid ; None let remove_gone_domains_cache xc = let current_domains = Xenctrl.domain_getinfolist xc 0 in Mutex.execute m (fun () -> let alive_domids = List.map (fun d -> d.Xenctrl.domid) current_domains in let known_domids = Hashtbl.fold (fun k _ acc -> k :: acc) cache [] in let gone_domids = set_difference known_domids alive_domids in List.iter (fun d -> debug "Remove domid %d in cache" d ; Hashtbl.remove cache d) gone_domids) let _introduceDomain = "@introduceDomain" let _releaseDomain = "@releaseDomain" exception Watch_overflow let watch_xenstore () = Xenctrl.with_intf (fun xc -> let interesting_paths = [ ["memory"; "initial-reservation"] ; ["memory"; "target"] ; ["control"; "feature-balloon"] ; ["data"; "updated"] ; ["memory"; "memory-offset"] ; ["memory"; "uncooperative"] ; ["memory"; "dynamic-min"] ; ["memory"; "dynamic-max"] ] in let watches domid = List.map (fun p -> Printf.sprintf "/local/domain/%d/%s" domid (String.concat "/" p)) interesting_paths in let module IntSet = Set.Make (struct type t = int let compare = compare end) in let watching_domids = ref IntSet.empty in let watch_token domid = Printf.sprintf "squeezed:domain-%d" domid in let look_for_different_domains () = let list_domains xc = let dis = Xenctrl.domain_getinfolist xc 0 in List.fold_left (fun set x -> if not x.Xenctrl.shutdown then IntSet.add x.Xenctrl.domid set else set) IntSet.empty dis in let existing = list_domains xc in let arrived = IntSet.diff existing !watching_domids in IntSet.iter (fun domid -> debug "Adding watches for domid: %d" domid ; List.iter (fun x -> try Client.immediate (get_client ()) (fun xs -> Client.watch xs x (watch_token domid)) with e -> error "watch path=%s token=%s: %s" x (watch_token domid) (Printexc.to_string e)) (watches domid)) arrived ; let gone = IntSet.diff !watching_domids existing in IntSet.iter (fun domid -> debug "Removing watches for domid: %d" domid ; List.iter (fun x -> try Client.immediate (get_client ()) (fun xs -> Client.unwatch xs x (watch_token domid)) with e -> error "unwatch path=%s token=%s: %s" x (watch_token domid) (Printexc.to_string e)) (watches domid)) gone ; watching_domids := existing ; Mutex.execute m (fun () -> IntSet.iter (Hashtbl.remove cache) gone ; IntSet.iter (fun domid -> try ignore (get_per_domain xc domid) with _ -> ()) arrived) in let incoming_watches = Queue.create () in let queue_overflowed = ref false in let incoming_watches_m = Mutex.create () in let incoming_watches_c = Condition.create () in let enqueue_watches event = Mutex.execute incoming_watches_m (fun () -> if Queue.length incoming_watches = 1024 then queue_overflowed := true else Queue.push event incoming_watches ; Condition.signal incoming_watches_c) in let dequeue_watches callback = try while true do let event = Mutex.execute incoming_watches_m (fun () -> while Queue.is_empty incoming_watches && not !queue_overflowed do Condition.wait incoming_watches_c incoming_watches_m done ; if !queue_overflowed then ( error "xenstore watch event queue overflow: this suggests \ the processing thread deadlocked somehow." ; raise Watch_overflow ) ; Queue.pop incoming_watches) in let () = callback event in () done with Watch_overflow -> () in let process_one_watch xc xs (path, token) = if path = _introduceDomain || path = _releaseDomain then look_for_different_domains () else match Astring.String.cuts ~empty:false ~sep:"/" path with | "local" :: "domain" :: domid :: rest when List.mem rest interesting_paths -> let value = try Some (Client.read xs path) with _ -> None in let domid = int_of_string domid in Mutex.execute m (fun () -> match get_per_domain xc domid with | None -> () | Some per_domain -> let key = "/" ^ String.concat "/" rest in debug "watch %s <- %s" key (Option.value ~default:"None" value) ; Hashtbl.replace per_domain.keys key value) | _ -> debug "Ignoring unexpected watch: %s" path in let register_for_watches xc = Client.immediate (get_client ()) (fun xs -> Client.set_watch_callback (get_client ()) enqueue_watches ; Client.watch xs _introduceDomain "squeezed" ; Client.watch xs _releaseDomain "squeezed" ; dequeue_watches (process_one_watch xc xs)) in while true do Xapi_stdext_pervasives.Pervasiveext.finally (fun () -> debug "(re)starting xenstore watch thread" ; Xenctrl.with_intf register_for_watches) (fun () -> Thread.delay 5.) done) let start_watch_xenstore_thread () = let (_ : Thread.t) = Thread.create (fun () -> while true do try watch_xenstore () with e -> error "watch_xenstore: %s" (Printexc.to_string e) ; Thread.delay 1. done) () in () let get_domain_type cnx domid = Mutex.execute m (fun () -> Option.fold ~none:`pv ~some:(fun d -> d.domain_type) (get_per_domain cnx domid)) let get_maxmem cnx domid = Mutex.execute m (fun () -> Option.fold ~none:0L ~some:(fun d -> d.maxmem) (get_per_domain cnx domid)) let set_maxmem_noexn xc domid mem = Mutex.execute m (fun () -> match get_per_domain xc domid with | None -> () | Some per_domain -> if per_domain.maxmem <> mem then ( debug "Xenctrl.domain_setmaxmem domid=%d max=%Ld (was=%Ld)" domid mem per_domain.maxmem ; try Xenctrl.domain_setmaxmem xc domid mem ; per_domain.maxmem <- mem with e -> error "Xenctrl.domain_setmaxmem domid=%d max=%Ld: (was=%Ld) %s" domid mem per_domain.maxmem (Printexc.to_string e) )) let read xc domid key = let x = Mutex.execute m (fun () -> match get_per_domain xc domid with | None -> None | Some per_domain -> if Hashtbl.mem per_domain.keys key then Hashtbl.find per_domain.keys key else let x = try Some (Client.immediate (get_client ()) (fun xs -> Client.read xs (per_domain.path ^ key))) with Xs_protocol.Enoent _ -> None in Hashtbl.replace per_domain.keys key x ; x) in match x with Some y -> y | None -> raise (Xs_protocol.Enoent key) * Write a new ( key , value ) pair into a domain 's directory in xenstore . Do n't write anything if the domain 's directory does n't exist . Do n't throw exceptions . write anything if the domain's directory doesn't exist. Don't throw exceptions. *) let write_noexn xc domid key value = match get_per_domain xc domid with | None -> () | Some per_domain -> ( if (not (Hashtbl.mem per_domain.keys key)) || Hashtbl.find per_domain.keys key <> Some value then try Client.transaction (get_client ()) (fun t -> ignore (Client.read t per_domain.path) ; Client.write t (per_domain.path ^ key) value) ; Hashtbl.replace per_domain.keys key (Some value) with e -> error "xenstore-write %d %s = %s failed: %s" domid key value (Printexc.to_string e) ) let exists xc domid key = try ignore (read xc domid key) ; true with Xs_protocol.Enoent _ -> false let rm_noexn xc domid key = match get_per_domain xc domid with | None -> () | Some per_domain -> ( Hashtbl.replace per_domain.keys key None ; try Client.immediate (get_client ()) (fun xs -> Client.rm xs (per_domain.path ^ key)) with e -> error "xenstore-rm %d %s: %s" domid key (Printexc.to_string e) ) let set_target_noexn cnx domid target_kib = write_noexn cnx domid _target (Int64.to_string target_kib) * Get a domain 's memory target . Throws Xenbus . Xb . Noent if the domain has been destroyed been destroyed *) let get_target cnx domid = Int64.of_string (read cnx domid _target) * a domain as uncooperative . Do n't throw an exception if the domain has been destroyed . been destroyed. *) let set_uncooperative_noexn cnx domid x = if x then write_noexn cnx domid _uncooperative "" else rm_noexn cnx domid _uncooperative * Query a domain 's uncooperative status . Throws Xenbus . Xb . Noent if the domain has been destroyed domain has been destroyed *) let get_uncooperative_noexn cnx domid = exists cnx domid _uncooperative let set_memory_offset_noexn cnx domid offset_kib = write_noexn cnx domid _memory_offset (Int64.to_string offset_kib) let get_memory_offset cnx domid = Int64.of_string (read cnx domid _memory_offset) let set_maxmem_noexn cnx domid target_kib = let offset_kib : int64 = try get_memory_offset cnx domid with _ -> 0L in let maxmem_kib = xen_max_offset_kib (get_domain_type cnx domid) +* target_kib +* offset_kib in set_maxmem_noexn cnx domid maxmem_kib let get_feature_balloon cnx domid = try ignore (read cnx domid _feature_balloon) ; true with Xs_protocol.Enoent _ -> false let get_guest_agent cnx domid = try ignore (read cnx domid _data_updated) ; true with Xs_protocol.Enoent _ -> false let get_initial_reservation cnx domid = Int64.of_string (read cnx domid _initial_reservation) let get_dynamic_min cnx domid = Int64.of_string (read cnx domid _dynamic_min) let get_dynamic_max cnx domid = Int64.of_string (read cnx domid _dynamic_max) end let when_domain_was_last_cooperative : (int, float) Hashtbl.t = Hashtbl.create 10 let update_cooperative_table host = let now = Unix.gettimeofday () in let alive_domids = List.map (fun d -> d.Squeeze.domid) host.Squeeze.domains in let known_domids = Hashtbl.fold (fun k _ acc -> k :: acc) when_domain_was_last_cooperative [] in let gone_domids = set_difference known_domids alive_domids in List.iter (Hashtbl.remove when_domain_was_last_cooperative) gone_domids ; let arrived_domids = set_difference alive_domids known_domids in List.iter (fun x -> Hashtbl.replace when_domain_was_last_cooperative x now) arrived_domids ; List.iter (fun d -> if (not d.Squeeze.can_balloon) || Squeeze.has_hit_target d.Squeeze.inaccuracy_kib d.Squeeze.memory_actual_kib d.Squeeze.target_kib then Hashtbl.replace when_domain_was_last_cooperative d.Squeeze.domid now) host.Squeeze.domains * Update all the flags in xenstore let update_cooperative_flags cnx = let now = Unix.gettimeofday () in Hashtbl.iter (fun domid last_time -> let old_value = Domain.get_uncooperative_noexn cnx domid in let new_value = now -. last_time > 20. in if old_value <> new_value then Domain.set_uncooperative_noexn cnx domid new_value) when_domain_was_last_cooperative let make_host ~verbose ~xc = while Int64.div ((Xenctrl.physinfo xc).Xenctrl.scrub_pages |> Int64.of_nativeint) 1024L <> 0L do ignore (Unix.select [] [] [] 0.25) done ; Some VMs are considered by us ( but not by xen ) to have an " initial - reservation " . For VMs which have never run ( eg which are still being built or restored ) we take the difference between memory_actual_kib and the reservation and subtract this manually from the host 's free memory . Note that we do n't get an atomic snapshot of system state so there is a natural race between the hypercalls . Hopefully the memory is being consumed fairly slowly and so the error is small . "initial-reservation". For VMs which have never run (eg which are still being built or restored) we take the difference between memory_actual_kib and the reservation and subtract this manually from the host's free memory. Note that we don't get an atomic snapshot of system state so there is a natural race between the hypercalls. Hopefully the memory is being consumed fairly slowly and so the error is small. *) Additionally we have the concept of a ' reservation ' separate from a domain which allows us to postpone domain creates until such time as there is lots of memory available . This minimises the chance that the remaining free memory will be too fragmented to actually use ( some xen structures require contiguous frames ) which allows us to postpone domain creates until such time as there is lots of memory available. This minimises the chance that the remaining free memory will be too fragmented to actually use (some xen structures require contiguous frames) *) let reserved_kib = ref 0L in let domain_infolist = Xenctrl.domain_getinfolist xc 0 in let domain_infolist = if !Squeeze.manage_domain_zero then domain_infolist else List.filter (fun di -> di.Xenctrl.domid > 0) domain_infolist in let cnx = xc in let domains = List.concat (List.map (fun di -> try let domain_type = Domain.get_domain_type cnx di.Xenctrl.domid in let memory_actual_kib = Xenctrl.pages_to_kib (Int64.of_nativeint di.Xenctrl.total_memory_pages) in let memory_shadow_kib = match domain_type with | `hvm | `pv_in_pvh -> ( try Memory.kib_of_mib (Int64.of_int (Xenctrl.shadow_allocation_get xc di.Xenctrl.domid)) with _ -> 0L ) | `pv -> 0L in let memory_max_kib = if di.Xenctrl.domid = 0 then 0L else Domain.maxmem_of_dominfo di domain_type in let can_balloon = Domain.get_feature_balloon cnx di.Xenctrl.domid in let has_guest_agent = Domain.get_guest_agent cnx di.Xenctrl.domid in let has_booted = can_balloon || has_guest_agent in Once the domain tells us it has booted , we assume it 's not currently ballooning and record the offset between memory_actual and target . We assume this is constant over the lifetime of the domain . currently ballooning and record the offset between memory_actual and target. We assume this is constant over the lifetime of the domain. *) let offset_kib : int64 = if not has_booted then 0L else try Domain.get_memory_offset cnx di.Xenctrl.domid with Xs_protocol.Enoent _ -> Our memory_actual_kib value was sampled before reading which means there is a slight race . The race is probably only noticable in the hypercall simulator . However we can fix it by resampling memory_actual * after * noticing the feature - balloon flag . xenstore which means there is a slight race. The race is probably only noticable in the hypercall simulator. However we can fix it by resampling memory_actual *after* noticing the feature-balloon flag. *) let target_kib = Domain.get_target cnx di.Xenctrl.domid in let memory_actual_kib' = Xenctrl.pages_to_kib (Int64.of_nativeint (Xenctrl.domain_getinfo xc di.Xenctrl.domid) .Xenctrl.total_memory_pages) in let offset_kib = memory_actual_kib' -* target_kib in debug "domid %d just %s; calibrating memory-offset = %Ld KiB" di.Xenctrl.domid ( match (can_balloon, has_guest_agent) with | true, false -> "advertised a balloon driver" | true, true -> "started a guest agent and advertised a balloon driver" | false, true -> "started a guest agent (but has no balloon driver)" | false, false -> ) offset_kib ; Domain.set_memory_offset_noexn cnx di.Xenctrl.domid offset_kib ; offset_kib in let memory_actual_kib = memory_actual_kib -* offset_kib in let domain = { Squeeze.domid= di.Xenctrl.domid ; can_balloon ; dynamic_min_kib= 0L ; dynamic_max_kib= 0L ; target_kib= 0L ; memory_actual_kib= 0L ; memory_max_kib ; inaccuracy_kib= 4L } in if not has_booted then ( let initial_reservation_kib = Domain.get_initial_reservation cnx di.Xenctrl.domid in let unaccounted_kib = max 0L (initial_reservation_kib -* memory_actual_kib -* memory_shadow_kib ) in reserved_kib := Int64.add !reserved_kib unaccounted_kib ; [ { domain with Squeeze.dynamic_min_kib= memory_max_kib ; dynamic_max_kib= memory_max_kib ; target_kib= memory_max_kib ; memory_actual_kib= memory_max_kib } ] ) else let target_kib = Domain.get_target cnx di.Xenctrl.domid in min and are written separately ; if we notice they let min_kib, max_kib = try ( Domain.get_dynamic_min cnx di.Xenctrl.domid , Domain.get_dynamic_max cnx di.Xenctrl.domid ) with _ -> (target_kib, target_kib) in [ { domain with Squeeze.dynamic_min_kib= min_kib ; dynamic_max_kib= max_kib ; target_kib ; memory_actual_kib } ] with | Xs_protocol.Enoent _ -> useful debug message is printed by the * functions [] | e -> if verbose then debug "Skipping domid %d: %s" di.Xenctrl.domid (Printexc.to_string e) ; []) domain_infolist) in let physinfo = Xenctrl.physinfo xc in let free_pages_kib = Xenctrl.pages_to_kib (Int64.of_nativeint physinfo.Xenctrl.free_pages) and scrub_pages_kib = Xenctrl.pages_to_kib (Int64.of_nativeint physinfo.Xenctrl.scrub_pages) and total_pages_kib = Xenctrl.pages_to_kib (Int64.of_nativeint physinfo.Xenctrl.total_pages) in let free_mem_kib = free_pages_kib +* scrub_pages_kib in let non_domain_reservations = Squeezed_state.total_reservations Squeezed_state._service domain_infolist in if verbose && non_domain_reservations <> 0L then debug "Total non-domain reservations = %Ld" non_domain_reservations ; reserved_kib := Int64.add !reserved_kib non_domain_reservations ; let host = Squeeze.make_host ~domains ~free_mem_kib:(Int64.sub free_mem_kib !reserved_kib) in update_cooperative_table host ; update_cooperative_flags cnx ; Domain.remove_gone_domains_cache xc ; let updates = Squeeze.IntMap.fold (fun domid domain updates -> if domain.Squeeze.target_kib < Domain.get_maxmem xc domid then Squeeze.IntMap.add domid domain.Squeeze.target_kib updates else updates) host.Squeeze.domid_to_domain Squeeze.IntMap.empty in Squeeze.IntMap.iter (Domain.set_maxmem_noexn xc) updates ; ( Printf.sprintf "F%Ld S%Ld R%Ld T%Ld" free_pages_kib scrub_pages_kib !reserved_kib total_pages_kib , host ) let execute_action ~xc action = try let domid = action.Squeeze.action_domid in let target_kib = action.Squeeze.new_target_kib in if target_kib < 0L then failwith (Printf.sprintf "Proposed target is negative (domid %d): %Ld" domid target_kib) ; let cnx = xc in let memory_max_kib = Domain.get_maxmem cnx domid in let can_balloon = Domain.get_feature_balloon cnx domid in if target_kib > memory_max_kib then ( Domain.set_maxmem_noexn cnx domid target_kib ; if can_balloon then Domain.set_target_noexn cnx domid target_kib else debug "Not setting target for domid: %d since no feature-balloon. Setting \ maxmem to %Ld" domid target_kib ) else ( if can_balloon then Domain.set_target_noexn cnx domid target_kib else debug "Not setting target for domid: %d since no feature-balloon. Setting \ maxmem to %Ld" domid target_kib ; Domain.set_maxmem_noexn cnx domid target_kib ) with e -> debug "Failed to reset balloon target (domid: %d) (target: %Ld): %s" action.Squeeze.action_domid action.Squeeze.new_target_kib (Printexc.to_string e) let extra_mem_to_keep = 8L ** mib let target_host_free_mem_kib = low_mem_emergency_pool +* extra_mem_to_keep let free_memory_tolerance_kib = 512L let io ~xc ~verbose = { verbose ; Squeeze.gettimeofday= Unix.gettimeofday ; make_host= (fun () -> make_host ~verbose ~xc) ; domain_setmaxmem= (fun domid kib -> execute_action ~xc {Squeeze.action_domid= domid; new_target_kib= kib}) ; wait= (fun delay -> ignore (Unix.select [] [] [] delay)) ; execute_action= (fun action -> execute_action ~xc action) ; target_host_free_mem_kib ; free_memory_tolerance_kib } let change_host_free_memory ~xc required_mem_kib success_condition = Squeeze.change_host_free_memory (io ~verbose:true ~xc) required_mem_kib success_condition let free_memory ~xc required_mem_kib = let io = io ~verbose:true ~xc in Squeeze.change_host_free_memory io (required_mem_kib +* io.Squeeze.target_host_free_mem_kib) (fun x -> x >= required_mem_kib +* io.Squeeze.target_host_free_mem_kib) let free_memory_range ~xc min_kib max_kib = let io = io ~verbose:true ~xc in Squeeze.free_memory_range io min_kib max_kib let is_balanced x = Int64.sub x target_host_free_mem_kib < free_memory_tolerance_kib let balance_memory ~xc = Squeeze.balance_memory (io ~verbose:true ~xc) let is_host_memory_unbalanced ~xc = Squeeze.is_host_memory_unbalanced (io ~verbose:false ~xc) If we want to manage domain 0 , we must write the policy settings to let configure_domain_zero () = Client.immediate (get_client ()) (fun xs -> Client.mkdir xs "/local/domain/0") ; Xenctrl.with_intf (fun xc -> Domain.write_noexn xc 0 _dynamic_min (Int64.to_string (Memory.kib_of_bytes_used !Squeeze.domain_zero_dynamic_min)) ; let dynamic_max = match !Squeeze.domain_zero_dynamic_max with | Some x -> Memory.kib_of_bytes_used x | None -> If this is the first time we 've started after boot then we can use the current domain 0 total_pages value . Otherwise we continue to use the version already in xenstore . use the current domain 0 total_pages value. Otherwise we continue to use the version already in xenstore. *) if Domain.exists xc 0 _dynamic_max then Int64.of_string (Domain.read xc 0 _dynamic_max) else let di = Xenctrl.domain_getinfo xc 0 in Xenctrl.pages_to_kib (Int64.of_nativeint di.Xenctrl.total_memory_pages) in Domain.write_noexn xc 0 _dynamic_max (Int64.to_string dynamic_max) ; if not (Domain.exists xc 0 _target) then Domain.write_noexn xc 0 _target (Int64.to_string dynamic_max) ; Domain.write_noexn xc 0 _feature_balloon "1")
c3cdb7a3efe623edea386cea4dce1e85a03a0b40b53b4624adf3aeddefd9ef89
azimut/shiny
buffers.lisp
(in-package :shiny) ;; TODO: ;; - right now it uses (at) to stop (word-play), ;; might be buffer-play can support other thing ;; ... I could have used (buffer-read) and (phasor-loop) ;; ... on the other hand it makes easy to play backwards ;; - Make it quickload-able ;; - Add slice support. With start and stop as relative values (defvar *buffers* (make-hash-table :test #'equal) "Global cache for all buffers loaded through (bbufer-load). Key is the (file-namestring). Example: \"sample.wav\" Value is the actual buffer object.") (defvar *sample-words* (make-hash-table :test #'equal)) (defvar *instruments* (make-hash-table)) (defvar *buffer-sets* (make-hash-table :test #'equal) "stores the sets of each buffer, KEY is the file-namestring VALUE is an (N 2) array") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DSPs helpers - These assume a blocksize of 1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-vug buffer-loop-play ((buffer buffer) rate start-pos loopstart loopend) (with-samples ((frame (phasor-loop rate start-pos loopstart loopend))) (buffer-read buffer frame :interpolation :cubic))) (dsp! play-lsample-f ((buf buffer) dur amp start-pos loopstart loopend rate left right lpf hpf bpf lpr hpr bpr reson resonq (downsamp fixnum) atk sus rel) "Plays given buffer for DUR in seconds. If greater than buffer loops from LOOPSTART to LOOPEND frame. It can be used to play an instrument sample and sustain the looped part. Or to play a slice of audio alone from the rest of the buffer." (:defaults nil 1 .5 0 0 0 1 1 1 0 0 0 1 1 1 0 2 0 0 .9 .1) (with-samples ((in (buffer-loop-play buf rate start-pos loopstart loopend)) (in (* in (envelope (make-envelope '(0 1 1 0) (list atk sus rel)) 1 dur #'incudine:free)))) (incudine.vug:maybe-expand in) ;; (unless (= 0d0 reson) (setf in (incudine.vug:reson in reson resonq))) ;; (unless (= 0 downsamp) (setf in (incudine.vug:downsamp downsamp in))) ;; (unless (= 0d0 lpf) (setf in (incudine.vug:lpf in lpf lpr))) (unless (= 0d0 hpf) (setf in (incudine.vug:hpf in hpf hpr))) (unless (= 0d0 bpf) (setf in (incudine.vug:hpf in bpf bpr))) (out (* amp (* left in)) (* amp (* right in))))) (dsp! bplay ((buf buffer) rate start-pos (loop-p boolean) amp left right custom-id lpf hpf bpf lpr hpr bpr end-frame (downsamp fixnum) reson resonq) "Plays given buffer without control for how long is played, it gracefully accepts negative rates or audio filters." (:defaults (incudine:incudine-missing-arg "BUFFER") 1 0 NIL 1 1 1 1 0 0 0 2 2 2 0 0 0 2) (with-samples ((in (buffer-play buf rate start-pos loop-p #'incudine:free end-frame))) (incudine.vug:maybe-expand in) (unless (= 0d0 reson) (setf in (incudine.vug:reson in reson resonq))) ;; (unless (= 0 downsamp) (setf in (incudine.vug:downsamp downsamp in))) ;; (unless (= 0d0 lpf) (setf in (incudine.vug:lpf in lpf lpr))) (unless (= 0d0 hpf) (setf in (incudine.vug:hpf in hpf hpr))) (unless (= 0d0 bpf) (setf in (incudine.vug:hpf in bpf bpr))) (out (* amp (* left in)) (* amp (* right in))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Buffer helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun list-buffers () (alexandria:hash-table-keys *buffers*)) (defun clean-buffers () (alexandria:maphash-values (lambda (x) (incudine:free x)) *buffers*) (clrhash *buffers*)) (defun list-words () (alexandria:hash-table-keys *sample-words*)) (defun node-alive (id) (node-id (node id))) (defun amp-node (time id &key (center 1f0) (radius .1) (period 1) (life 3)) (declare (sample time) (integer id)) "sends random rate changes to the node ID LIFE is needed to avoid early check of the node" (let ((alive (node-id (node id)))) (when (or alive (> life 0)) (set-control id :amp (funcall (cm:pick '+ '+ '+ '+ '+ '+ '-) (cosr center radius 10))) (aat (+ time (* *sample-rate* period)) #'amp-node it id :life (- life 1))))) (defun corrupt-node (time id &key (center 1f0) (radius .1) (period 1) (life 3)) (declare (sample time) (integer id)) "sends random rate changes to the node ID LIFE is needed to avoid early check of the node" (let ((alive (node-id (node id)))) (when (or alive (> life 0)) (set-control id :rate (funcall (cm:pick '+ '+ '+ '+ '+ '+ '-) (cosr center radius 10))) (aat (+ time (* *sample-rate* period)) #'corrupt-node it id :life (- life 1))))) (defun pitch-to-ratio (p) (declare (integer p)) "relative midi pitch to frequency ratio" (expt 2 (/ p 12))) (defun beat-to-ratio (beat-length sample-rate dur) (declare (sample sample-rate) (number beat-length dur)) "given a BEAT-LENGTH and DURation in seconds returns a rate" (let* ((samples-to-play (* dur sample-rate)) (samples-per-beat (/ samples-to-play beat-length)) (rate (/ samples-per-beat sample-rate))) rate)) (defun bbuffer-load (filename &optional alias-key) "buffer-load wrapper for global hash caching and easy access FILENAME is a normal string of a path where to load the file (bbuffer-load \"/home/sendai/curso/furi-dream-cc.wav\")" (declare (type (or string pathname) filename)) (let* ((filepath (resolve-path filename)) (hkey (if alias-key alias-key (file-namestring filepath))) (buf (gethash hkey *buffers*))) (if (not buf) (setf (gethash hkey *buffers*) (buffer-load filepath)) buf))) ;;-------------------------------------------------- ;; Single buffer play (defun bbplay (buf &key (rate 1d0 rate-p) (rpitch 0 rpitch-p) (beat-length 1f0 beat-length-p) (start-pos 0d0) (loop-p nil) (amp 1d0) (id 2 id-p) (lpf 0) (hpf 0) (bpf 0) (left 1d0) (right 1d0) (downsamp 1 downsamp-p) (pan .5 pan-p) (lpr 2) (hpr 2) (bpr 2) (reson 0) (resonq 2) (end-pos 0 end-pos-p) (set 0 set-p)) (declare (fixnum rpitch) (boolean loop-p) (number lpf hpf bpf lpr hpr bpr pan reson resonq end-pos rate beat-length amp left right) (unsigned-byte downsamp set id)) "plays the provided buffer either by PAN value between 0f0 and 1f0 RATE plays the buffer to play at rate RPITCH bends the whole buffer rate to play to the new pitch offset START-POS in samples BEAT-LENGTH stretch the whole buffer to play for N beats" (when (or (symbolp buf) (stringp buf) (characterp buf)) (let ((b (gethash buf *buffers*))) (when b (setf buf b)))) ;; TODO: big check so we can send nil to beat-length without crashing (when (incudine:buffer-p buf) (let* ((sample-rate (buffer-sample-rate buf)) (frames (if end-pos-p end-pos (buffer-frames buf))) (sets (if set-p (gethash (file-namestring (buffer-file buf)) *buffer-sets*) NIL)) (set (if (and set-p sets) (mod set (array-dimension sets 0)) NIL)) (start-pos (if (and set-p sets) (aref sets set 0) start-pos)) (end-pos (if (and set-p sets) (aref sets set 1) frames)) (dur (/ (- end-pos start-pos) sample-rate))) (when rpitch-p (mulf rate (pitch-to-ratio rpitch))) (when beat-length-p need to calculate the total duration in sec ;; to provide it to (beat-to-ratio (mulf rate (beat-to-ratio beat-length sample-rate dur))) (setf dur (/ dur (abs rate))) ;; "hack" to work with buffer-play vug (when (< rate 0) (setf start-pos (- frames (/ frames 20)))) (when pan-p (setf pan (alexandria:clamp pan 0f0 1f0)) (cond ((> pan .5) (decf left (* 2 (- pan .5)))) ((< pan .5) (decf right (* 2 (abs (- pan .5))))))) (if (and set-p sets) (if id-p (play-lsample-f buf dur amp start-pos :rate rate :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :left left :right right :reson reson :resonq resonq :sus 1 :rel 0 :downsamp downsamp :id id) (play-lsample-f buf dur amp start-pos :rate rate :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :reson reson :resonq resonq :sus 1 :rel 0 :downsamp downsamp :left left :right right)) (if id-p (bplay buf rate start-pos loop-p amp left right :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :reson reson :resonq resonq :downsamp downsamp :id id) (bplay buf rate start-pos loop-p amp left right :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :reson reson :resonq resonq :downsamp downsamp))) dur))) ;;------------------------------------------------------ ;; Description: These one help slicing buffers into smaller pieces and ;; reference those by a shortname. ;; ;; Slice of a single buffer, dedicated to words or phrases (defstruct phrase "file-namestring and time in seconds at which start playing and for how long" filename start-at dur) (defun put-phrase (word filename start-at dur) (declare (string word filename) (number start-at dur)) "creates a reference on global hash for WORD in FILENAME begining at START-AT for DUR (put-phrase \"nothing\" \"furi-better-cc.wav\" 1.7 1.9)" (setf (gethash word *sample-words*) (make-phrase :filename filename :start-at start-at :dur dur))) (defun word-play (phrase &key (rate 1) (rpitch 1 rpitch-p) (beat-length 1 beat-length-p) (loop-p nil) (amp 1f0) (id 2 id-p) corrupt (downsamp 0 downsamp-p) (left 1f0) (right 1f0) (pan 1f0 pan-p) (lpf 0) (hpf 0) (bpf 0) (lpr 1) (hpr 1) (bpr 1) (corrupt-center 1f0) (corrupt-radius .1) (corrupt-period 1)) (declare (integer rpitch id) (boolean loop-p)) "bplay wrapper to play the phrase provided (word-play \"time\") (word-play \"time\" :rate 2) (word-play \"time\" :rpitch 7) (word-play \"time\" :beat-length 4)" (when (or (and phrase (stringp phrase)) (and phrase (not (eq phrase :end-of-data)))) (let* ((obj (gethash phrase *sample-words*)) ;; Seconds (str (phrase-start-at obj)) (dur (phrase-dur obj)) (buf (gethash (phrase-filename obj) *buffers*)) (sample-rate (buffer-sample-rate buf)) ;; Frames (start-pos (* sample-rate str)) (end-pos (+ start-pos (* sample-rate dur)))) ;; pitch to ratio - from sonic-pi (when rpitch-p (mulf rate (pitch-to-ratio rpitch))) ;; Update duration now based on the rate (setf dur (/ dur (abs rate))) ;; play for beat-length (when beat-length-p (mulf rate (beat-to-ratio beat-length sample-rate dur))) ;; change where to start when played backwards (when (< rate 0) (rotatef start-pos end-pos)) (when pan-p (setf pan (alexandria:clamp pan 0f0 1f0)) (cond ((> pan .5) (decf left (* 2 (- pan .5)))) ((< pan .5) (decf right (* 2 (abs (- pan .5))))))) ;; start voice (if id-p (play-lsample-f buf dur amp start-pos :downsamp downsamp :rate rate :left left :right right :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :id id) (play-lsample-f buf dur amp start-pos :downsamp downsamp :rate rate :left left :right right :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :amp amp)) (when corrupt (corrupt-node (now) id :center corrupt-center :radius corrupt-radius :period corrupt-period)) T))) ;; ? ;;-------------------------------------------------- ;; An instrument is composed of different sound files that can be referenced by calling one function with ;; different pitches. They also might need a sustain to ;; play longer than designed without change pitch. ;; NOTE: Using some of ormf's code. ;;-------------------------------------------------- (defclass instrument () ((name :initarg :name :documentation "relative filename path") (dir :initarg :dir :documentation "absolute directory path where to look for samples") (keys :initarg :keys :initform (make-array 127 :initial-element nil) :documentation "stores key class elements"))) (defun make-instrument (name directory) (declare (symbol name) (string directory)) (unless (gethash name *instruments*) (setf (gethash name *instruments*) (make-instance 'instrument :name name :dir directory)))) (defun list-instruments () (alexandria:hash-table-keys *instruments*)) (defun clean-instruments () (clean-buffers) (clrhash *instruments*)) ;;-------------------------------------------------- (defclass key () ((filename :initarg :filename :documentation "just filename without path, used to lookup into *buffers* hash") (keynum :initarg :keynum :documentation "midi keynum") (startpos :initarg :startpos :documentation "initial start position") (loopstart :initarg :loopstart :documentation "loop start position") (loopend :initarg :loopend :documentation "loop end position"))) (defun get-pure-keys (keys) "Returns a list of keys that match the array index and thus won't be pitchbended." (loop :for i :from 0 :for ckey :across keys :when (and ckey (= i (slot-value ckey 'keynum))) :collect i)) (defun get-new-mappings-hash (akeys) (loop :for (x y) :on (get-pure-keys akeys) :with first-p = T :with hkeys = (make-hash-table) :finally (return hkeys) :do (cond ((and first-p x y) (setf first-p nil) At least 2 notes (appendf (gethash x hkeys) (append (iota x) (iota (round (/ (- y x) 2)) :start (+ 1 x)))) (appendf (gethash y hkeys) (iota (- y (+ x (round (/ (- y x) 2)))) :start (+ x (round (/ (- y x) 2)))))) Only 1 note ((and first-p x) (appendf (gethash x hkeys) (append (iota x :start 0) (iota (- 126 x) :start (1+ x))))) ;; Middle ((and x y) (appendf (gethash x hkeys) (iota (round (/ (- y x) 2)) :start x)) (appendf (gethash y hkeys) (iota (round (/ (- y x) 2)) :start (+ x (round (/ (- y x) 2)))))) ;; Final sequence ((and (not y) (not first-p) x) (appendf (gethash x hkeys) (iota (- 126 x) :start (1+ x))))))) (defun fill-notes (keynum iname) (let* ((akeys (slot-value (gethash iname *instruments*) 'keys))) (loop :for k :in (gethash keynum (get-new-mappings-hash akeys)) :do (setf (aref akeys k) (aref akeys keynum))))) (defun push-note (iname keynum filename &optional (startpos 0) loopstart loopend) (declare (symbol iname) (unsigned-byte keynum) (string filename)) (when-let ((instrument (gethash iname *instruments*))) (with-slots (dir keys) instrument (let* ((fullpath (concatenate 'string dir filename)) (buf (bbuffer-load fullpath)) (buf-size (buffer-size buf))) (setf loopend buf-size loopstart buf-size) (setf (aref keys keynum) (make-instance 'key :filename filename :keynum keynum :startpos startpos :loopstart loopstart :loopend loopend)) (fill-notes keynum iname))))) (defun push-note-parsed (iname filename &optional (startpos 0) loopstart loopend) (declare (symbol iname) (string filename)) (when-let ((instrument (gethash iname *instruments*)) (keynum (note-name-to-midi-number filename))) (with-slots (dir keys) instrument (let* ((fullpath (concatenate 'string dir filename)) (buf (bbuffer-load fullpath)) (buf-size (buffer-size buf))) (setf loopend buf-size loopstart buf-size) (setf (aref keys keynum) (make-instance 'key :filename filename :keynum keynum :startpos startpos :loopstart loopstart :loopend loopend)) (fill-notes keynum iname))))) (defun load-instrument (iname) (when-let ((instrument (gethash iname *instruments*))) (with-slots (dir) instrument (loop :for f :in (directory (concatenate 'string dir "*.wav")) :do (push-note-parsed iname (file-namestring f)))))) (defun play-instrument (name nkeynum &key (dur 1) (amp 1) (rpitch 0) (id 222 id-p) (downsamp 0) (reson 0) (left 1) (right 1) (lpf 0) (hpf 0) (bpf 0) (lpr 1) (hpr 1) (bpr 1)) (declare (symbol name) (integer nkeynum) (number dur amp rpitch)) (with-slots (keys) (gethash name *instruments*) (with-slots (filename loopend loopstart keynum) (aref keys nkeynum) (let* ((buf (gethash filename *buffers*)) (relative-pitch (- nkeynum keynum)) (rate (pitch-to-ratio (if (not (= 0 rpitch)) rpitch relative-pitch)))) (if id-p (play-lsample-f buf dur amp :id id :rate rate :downsamp downsamp :reson reson :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :left left :right right) (play-lsample-f buf dur amp :rate rate :downsamp downsamp :reson reson :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :left left :right right))))))
null
https://raw.githubusercontent.com/azimut/shiny/774381a9bde21c4ec7e7092c7516dd13a5a50780/lib/buffers.lisp
lisp
TODO: - right now it uses (at) to stop (word-play), might be buffer-play can support other thing ... I could have used (buffer-read) and (phasor-loop) ... on the other hand it makes easy to play backwards - Make it quickload-able - Add slice support. With start and stop as relative values Buffer helpers -------------------------------------------------- Single buffer play TODO: big check so we can send nil to beat-length without crashing to provide it to (beat-to-ratio "hack" to work with buffer-play vug ------------------------------------------------------ Description: These one help slicing buffers into smaller pieces and reference those by a shortname. Slice of a single buffer, dedicated to words or phrases Seconds Frames pitch to ratio - from sonic-pi Update duration now based on the rate play for beat-length change where to start when played backwards start voice ? -------------------------------------------------- An instrument is composed of different sound files different pitches. They also might need a sustain to play longer than designed without change pitch. NOTE: Using some of ormf's code. -------------------------------------------------- -------------------------------------------------- Middle Final sequence
(in-package :shiny) (defvar *buffers* (make-hash-table :test #'equal) "Global cache for all buffers loaded through (bbufer-load). Key is the (file-namestring). Example: \"sample.wav\" Value is the actual buffer object.") (defvar *sample-words* (make-hash-table :test #'equal)) (defvar *instruments* (make-hash-table)) (defvar *buffer-sets* (make-hash-table :test #'equal) "stores the sets of each buffer, KEY is the file-namestring VALUE is an (N 2) array") DSPs helpers - These assume a blocksize of 1 (define-vug buffer-loop-play ((buffer buffer) rate start-pos loopstart loopend) (with-samples ((frame (phasor-loop rate start-pos loopstart loopend))) (buffer-read buffer frame :interpolation :cubic))) (dsp! play-lsample-f ((buf buffer) dur amp start-pos loopstart loopend rate left right lpf hpf bpf lpr hpr bpr reson resonq (downsamp fixnum) atk sus rel) "Plays given buffer for DUR in seconds. If greater than buffer loops from LOOPSTART to LOOPEND frame. It can be used to play an instrument sample and sustain the looped part. Or to play a slice of audio alone from the rest of the buffer." (:defaults nil 1 .5 0 0 0 1 1 1 0 0 0 1 1 1 0 2 0 0 .9 .1) (with-samples ((in (buffer-loop-play buf rate start-pos loopstart loopend)) (in (* in (envelope (make-envelope '(0 1 1 0) (list atk sus rel)) 1 dur #'incudine:free)))) (incudine.vug:maybe-expand in) (unless (= 0d0 reson) (setf in (incudine.vug:reson in reson resonq))) (unless (= 0 downsamp) (setf in (incudine.vug:downsamp downsamp in))) (unless (= 0d0 lpf) (setf in (incudine.vug:lpf in lpf lpr))) (unless (= 0d0 hpf) (setf in (incudine.vug:hpf in hpf hpr))) (unless (= 0d0 bpf) (setf in (incudine.vug:hpf in bpf bpr))) (out (* amp (* left in)) (* amp (* right in))))) (dsp! bplay ((buf buffer) rate start-pos (loop-p boolean) amp left right custom-id lpf hpf bpf lpr hpr bpr end-frame (downsamp fixnum) reson resonq) "Plays given buffer without control for how long is played, it gracefully accepts negative rates or audio filters." (:defaults (incudine:incudine-missing-arg "BUFFER") 1 0 NIL 1 1 1 1 0 0 0 2 2 2 0 0 0 2) (with-samples ((in (buffer-play buf rate start-pos loop-p #'incudine:free end-frame))) (incudine.vug:maybe-expand in) (unless (= 0d0 reson) (setf in (incudine.vug:reson in reson resonq))) (unless (= 0 downsamp) (setf in (incudine.vug:downsamp downsamp in))) (unless (= 0d0 lpf) (setf in (incudine.vug:lpf in lpf lpr))) (unless (= 0d0 hpf) (setf in (incudine.vug:hpf in hpf hpr))) (unless (= 0d0 bpf) (setf in (incudine.vug:hpf in bpf bpr))) (out (* amp (* left in)) (* amp (* right in))))) (defun list-buffers () (alexandria:hash-table-keys *buffers*)) (defun clean-buffers () (alexandria:maphash-values (lambda (x) (incudine:free x)) *buffers*) (clrhash *buffers*)) (defun list-words () (alexandria:hash-table-keys *sample-words*)) (defun node-alive (id) (node-id (node id))) (defun amp-node (time id &key (center 1f0) (radius .1) (period 1) (life 3)) (declare (sample time) (integer id)) "sends random rate changes to the node ID LIFE is needed to avoid early check of the node" (let ((alive (node-id (node id)))) (when (or alive (> life 0)) (set-control id :amp (funcall (cm:pick '+ '+ '+ '+ '+ '+ '-) (cosr center radius 10))) (aat (+ time (* *sample-rate* period)) #'amp-node it id :life (- life 1))))) (defun corrupt-node (time id &key (center 1f0) (radius .1) (period 1) (life 3)) (declare (sample time) (integer id)) "sends random rate changes to the node ID LIFE is needed to avoid early check of the node" (let ((alive (node-id (node id)))) (when (or alive (> life 0)) (set-control id :rate (funcall (cm:pick '+ '+ '+ '+ '+ '+ '-) (cosr center radius 10))) (aat (+ time (* *sample-rate* period)) #'corrupt-node it id :life (- life 1))))) (defun pitch-to-ratio (p) (declare (integer p)) "relative midi pitch to frequency ratio" (expt 2 (/ p 12))) (defun beat-to-ratio (beat-length sample-rate dur) (declare (sample sample-rate) (number beat-length dur)) "given a BEAT-LENGTH and DURation in seconds returns a rate" (let* ((samples-to-play (* dur sample-rate)) (samples-per-beat (/ samples-to-play beat-length)) (rate (/ samples-per-beat sample-rate))) rate)) (defun bbuffer-load (filename &optional alias-key) "buffer-load wrapper for global hash caching and easy access FILENAME is a normal string of a path where to load the file (bbuffer-load \"/home/sendai/curso/furi-dream-cc.wav\")" (declare (type (or string pathname) filename)) (let* ((filepath (resolve-path filename)) (hkey (if alias-key alias-key (file-namestring filepath))) (buf (gethash hkey *buffers*))) (if (not buf) (setf (gethash hkey *buffers*) (buffer-load filepath)) buf))) (defun bbplay (buf &key (rate 1d0 rate-p) (rpitch 0 rpitch-p) (beat-length 1f0 beat-length-p) (start-pos 0d0) (loop-p nil) (amp 1d0) (id 2 id-p) (lpf 0) (hpf 0) (bpf 0) (left 1d0) (right 1d0) (downsamp 1 downsamp-p) (pan .5 pan-p) (lpr 2) (hpr 2) (bpr 2) (reson 0) (resonq 2) (end-pos 0 end-pos-p) (set 0 set-p)) (declare (fixnum rpitch) (boolean loop-p) (number lpf hpf bpf lpr hpr bpr pan reson resonq end-pos rate beat-length amp left right) (unsigned-byte downsamp set id)) "plays the provided buffer either by PAN value between 0f0 and 1f0 RATE plays the buffer to play at rate RPITCH bends the whole buffer rate to play to the new pitch offset START-POS in samples BEAT-LENGTH stretch the whole buffer to play for N beats" (when (or (symbolp buf) (stringp buf) (characterp buf)) (let ((b (gethash buf *buffers*))) (when b (setf buf b)))) (when (incudine:buffer-p buf) (let* ((sample-rate (buffer-sample-rate buf)) (frames (if end-pos-p end-pos (buffer-frames buf))) (sets (if set-p (gethash (file-namestring (buffer-file buf)) *buffer-sets*) NIL)) (set (if (and set-p sets) (mod set (array-dimension sets 0)) NIL)) (start-pos (if (and set-p sets) (aref sets set 0) start-pos)) (end-pos (if (and set-p sets) (aref sets set 1) frames)) (dur (/ (- end-pos start-pos) sample-rate))) (when rpitch-p (mulf rate (pitch-to-ratio rpitch))) (when beat-length-p need to calculate the total duration in sec (mulf rate (beat-to-ratio beat-length sample-rate dur))) (setf dur (/ dur (abs rate))) (when (< rate 0) (setf start-pos (- frames (/ frames 20)))) (when pan-p (setf pan (alexandria:clamp pan 0f0 1f0)) (cond ((> pan .5) (decf left (* 2 (- pan .5)))) ((< pan .5) (decf right (* 2 (abs (- pan .5))))))) (if (and set-p sets) (if id-p (play-lsample-f buf dur amp start-pos :rate rate :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :left left :right right :reson reson :resonq resonq :sus 1 :rel 0 :downsamp downsamp :id id) (play-lsample-f buf dur amp start-pos :rate rate :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :reson reson :resonq resonq :sus 1 :rel 0 :downsamp downsamp :left left :right right)) (if id-p (bplay buf rate start-pos loop-p amp left right :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :reson reson :resonq resonq :downsamp downsamp :id id) (bplay buf rate start-pos loop-p amp left right :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :reson reson :resonq resonq :downsamp downsamp))) dur))) (defstruct phrase "file-namestring and time in seconds at which start playing and for how long" filename start-at dur) (defun put-phrase (word filename start-at dur) (declare (string word filename) (number start-at dur)) "creates a reference on global hash for WORD in FILENAME begining at START-AT for DUR (put-phrase \"nothing\" \"furi-better-cc.wav\" 1.7 1.9)" (setf (gethash word *sample-words*) (make-phrase :filename filename :start-at start-at :dur dur))) (defun word-play (phrase &key (rate 1) (rpitch 1 rpitch-p) (beat-length 1 beat-length-p) (loop-p nil) (amp 1f0) (id 2 id-p) corrupt (downsamp 0 downsamp-p) (left 1f0) (right 1f0) (pan 1f0 pan-p) (lpf 0) (hpf 0) (bpf 0) (lpr 1) (hpr 1) (bpr 1) (corrupt-center 1f0) (corrupt-radius .1) (corrupt-period 1)) (declare (integer rpitch id) (boolean loop-p)) "bplay wrapper to play the phrase provided (word-play \"time\") (word-play \"time\" :rate 2) (word-play \"time\" :rpitch 7) (word-play \"time\" :beat-length 4)" (when (or (and phrase (stringp phrase)) (and phrase (not (eq phrase :end-of-data)))) (let* ((obj (gethash phrase *sample-words*)) (str (phrase-start-at obj)) (dur (phrase-dur obj)) (buf (gethash (phrase-filename obj) *buffers*)) (sample-rate (buffer-sample-rate buf)) (start-pos (* sample-rate str)) (end-pos (+ start-pos (* sample-rate dur)))) (when rpitch-p (mulf rate (pitch-to-ratio rpitch))) (setf dur (/ dur (abs rate))) (when beat-length-p (mulf rate (beat-to-ratio beat-length sample-rate dur))) (when (< rate 0) (rotatef start-pos end-pos)) (when pan-p (setf pan (alexandria:clamp pan 0f0 1f0)) (cond ((> pan .5) (decf left (* 2 (- pan .5)))) ((< pan .5) (decf right (* 2 (abs (- pan .5))))))) (if id-p (play-lsample-f buf dur amp start-pos :downsamp downsamp :rate rate :left left :right right :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :id id) (play-lsample-f buf dur amp start-pos :downsamp downsamp :rate rate :left left :right right :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :amp amp)) (when corrupt (corrupt-node (now) id :center corrupt-center :radius corrupt-radius :period corrupt-period)) that can be referenced by calling one function with (defclass instrument () ((name :initarg :name :documentation "relative filename path") (dir :initarg :dir :documentation "absolute directory path where to look for samples") (keys :initarg :keys :initform (make-array 127 :initial-element nil) :documentation "stores key class elements"))) (defun make-instrument (name directory) (declare (symbol name) (string directory)) (unless (gethash name *instruments*) (setf (gethash name *instruments*) (make-instance 'instrument :name name :dir directory)))) (defun list-instruments () (alexandria:hash-table-keys *instruments*)) (defun clean-instruments () (clean-buffers) (clrhash *instruments*)) (defclass key () ((filename :initarg :filename :documentation "just filename without path, used to lookup into *buffers* hash") (keynum :initarg :keynum :documentation "midi keynum") (startpos :initarg :startpos :documentation "initial start position") (loopstart :initarg :loopstart :documentation "loop start position") (loopend :initarg :loopend :documentation "loop end position"))) (defun get-pure-keys (keys) "Returns a list of keys that match the array index and thus won't be pitchbended." (loop :for i :from 0 :for ckey :across keys :when (and ckey (= i (slot-value ckey 'keynum))) :collect i)) (defun get-new-mappings-hash (akeys) (loop :for (x y) :on (get-pure-keys akeys) :with first-p = T :with hkeys = (make-hash-table) :finally (return hkeys) :do (cond ((and first-p x y) (setf first-p nil) At least 2 notes (appendf (gethash x hkeys) (append (iota x) (iota (round (/ (- y x) 2)) :start (+ 1 x)))) (appendf (gethash y hkeys) (iota (- y (+ x (round (/ (- y x) 2)))) :start (+ x (round (/ (- y x) 2)))))) Only 1 note ((and first-p x) (appendf (gethash x hkeys) (append (iota x :start 0) (iota (- 126 x) :start (1+ x))))) ((and x y) (appendf (gethash x hkeys) (iota (round (/ (- y x) 2)) :start x)) (appendf (gethash y hkeys) (iota (round (/ (- y x) 2)) :start (+ x (round (/ (- y x) 2)))))) ((and (not y) (not first-p) x) (appendf (gethash x hkeys) (iota (- 126 x) :start (1+ x))))))) (defun fill-notes (keynum iname) (let* ((akeys (slot-value (gethash iname *instruments*) 'keys))) (loop :for k :in (gethash keynum (get-new-mappings-hash akeys)) :do (setf (aref akeys k) (aref akeys keynum))))) (defun push-note (iname keynum filename &optional (startpos 0) loopstart loopend) (declare (symbol iname) (unsigned-byte keynum) (string filename)) (when-let ((instrument (gethash iname *instruments*))) (with-slots (dir keys) instrument (let* ((fullpath (concatenate 'string dir filename)) (buf (bbuffer-load fullpath)) (buf-size (buffer-size buf))) (setf loopend buf-size loopstart buf-size) (setf (aref keys keynum) (make-instance 'key :filename filename :keynum keynum :startpos startpos :loopstart loopstart :loopend loopend)) (fill-notes keynum iname))))) (defun push-note-parsed (iname filename &optional (startpos 0) loopstart loopend) (declare (symbol iname) (string filename)) (when-let ((instrument (gethash iname *instruments*)) (keynum (note-name-to-midi-number filename))) (with-slots (dir keys) instrument (let* ((fullpath (concatenate 'string dir filename)) (buf (bbuffer-load fullpath)) (buf-size (buffer-size buf))) (setf loopend buf-size loopstart buf-size) (setf (aref keys keynum) (make-instance 'key :filename filename :keynum keynum :startpos startpos :loopstart loopstart :loopend loopend)) (fill-notes keynum iname))))) (defun load-instrument (iname) (when-let ((instrument (gethash iname *instruments*))) (with-slots (dir) instrument (loop :for f :in (directory (concatenate 'string dir "*.wav")) :do (push-note-parsed iname (file-namestring f)))))) (defun play-instrument (name nkeynum &key (dur 1) (amp 1) (rpitch 0) (id 222 id-p) (downsamp 0) (reson 0) (left 1) (right 1) (lpf 0) (hpf 0) (bpf 0) (lpr 1) (hpr 1) (bpr 1)) (declare (symbol name) (integer nkeynum) (number dur amp rpitch)) (with-slots (keys) (gethash name *instruments*) (with-slots (filename loopend loopstart keynum) (aref keys nkeynum) (let* ((buf (gethash filename *buffers*)) (relative-pitch (- nkeynum keynum)) (rate (pitch-to-ratio (if (not (= 0 rpitch)) rpitch relative-pitch)))) (if id-p (play-lsample-f buf dur amp :id id :rate rate :downsamp downsamp :reson reson :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :left left :right right) (play-lsample-f buf dur amp :rate rate :downsamp downsamp :reson reson :lpf lpf :hpf hpf :bpf bpf :lpr lpr :hpr hpr :bpr bpr :left left :right right))))))
675007c9aa076b32fc3a416185915954c5ff601167a8cb2e624fd79b0aee9419
EMSL-NMR-EPR/Haskell-MFAPipe-Executable
Stoichiometry.hs
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # ----------------------------------------------------------------------------- -- | -- Module : Science.Chemistry.Stoichiometry Copyright : 2016 - 17 Pacific Northwest National Laboratory -- License : ECL-2.0 (see the LICENSE file in the distribution) -- -- Maintainer : -- Stability : experimental -- Portability : portable -- -- This module exports classes and types for the construction of sparse and -- dense stoichiometric models, including stoichiometry matrices. ----------------------------------------------------------------------------- module Science.Chemistry.Stoichiometry * HasStoichiometry class HasStoichiometry(..) * MutableStoichiometricModel class , MutableStoichiometricModel(..) , modifyStoichiometricModel * models , Sparse(..) , Dense(..) -- ** Conversion , sparseToDense -- * Utility functions , mapAccumStoichiometricModelM , mapAccumStoichiometricModel ) where import Control.Applicative (liftA2, liftA3) import qualified Control.Lens import Control.Monad.Reader.Class (MonadReader()) import qualified Control.Monad.Reader.Class import Control.Monad.State.Class (MonadState()) import qualified Control.Monad.State.Class import qualified Control.Monad.Trans.Reader import qualified Control.Monad.Trans.State.Strict as Control.Monad.Trans.State import Data.Function (on) import qualified Data.Functor.Identity import Data.Map.Strict (Map) import qualified Data.Map.Strict import Data.Maybe (catMaybes) import Data.Monoid (Sum(..)) import Data.Set (Set) import qualified Data.Set import Numeric.LinearAlgebra.HMatrix (Container(), Matrix, Vector) import qualified Numeric.LinearAlgebra.HMatrix import Science.Chemistry.Types | The ' HasStoichiometry ' class is used for types that have stoichiometry , where : -- -- * @a@ is the type of chemical species; and, -- -- * @r@ is the type of the environment. -- class (Ord a) => HasStoichiometry a r | r -> a where # MINIMAL assertStoichiometryM # | @assertStoichiometryM f g r@ is a computation that asserts the stoichiometry of @r@ , given the functions @f@ and @g@ , in the context of an arbitrary ' Monad ' . assertStoichiometryM :: (Monad m) => (a -> StoichiometricCoefficient -> m ()) ^ Assert chemical species with ' StoichiometricCoefficient ' . -> (Either a a -> m ()) -- ^ Assert chemical species, where 'Left' and 'Right' denote, -- respectively, intermediates and reagents/products. -> r -- ^ Environment -> m () | The ' MutableStoichiometricModel ' class is used for types that are mutable stoichiometric models , where : -- * @i@ is the type of chemical reaction indices ; -- -- * @a@ is the type of chemical species; and, -- -- * @s@ is the type of the state of the stoichiometric model. -- class (Ord i, Ord a) => MutableStoichiometricModel i a s | s -> i, s -> a where # MINIMAL modifyStoichiometricModelM # | @modifyStoichiometricModelM i@ is a computation that modifies the current state of a stoichiometric model . modifyStoichiometricModelM :: (MonadReader r m, MonadState s m, HasStoichiometry a r) => i -> m () | @modifyStoichiometricModel i r s@ is a computation that modifies the current state of the stoichiometric model @s@ , given the environment @r@. modifyStoichiometricModel :: (HasStoichiometry a r, MutableStoichiometricModel i a s) => i -> r -> s -> s modifyStoichiometricModel ix r = Data.Functor.Identity.runIdentity . Control.Monad.Trans.State.execStateT (Control.Monad.Trans.Reader.runReaderT (modifyStoichiometricModelM ix) r) -- | The 'mapAccumStoichiometricModelM' applies 'modifyStoichiometricModelM' to each element of a structure, passing the accumulated stoichiometric model from left to right. mapAccumStoichiometricModelM :: (Foldable f, Monad m, HasStoichiometry a r, MutableStoichiometricModel i a s) => f (i, r) -> s -> m s mapAccumStoichiometricModelM = Control.Monad.Trans.State.execStateT . mapM_ (uncurry (\ix r -> Control.Monad.Trans.Reader.runReaderT (modifyStoichiometricModelM ix) r)) -- | The 'mapAccumStoichiometricModel' applies 'modifyStoichiometricModel' to each element of a structure, passing the accumulated stoichiometric model from left to right. mapAccumStoichiometricModel :: (Foldable f, HasStoichiometry a r, MutableStoichiometricModel i a s) => f (i, r) -> s -> s mapAccumStoichiometricModel = (Data.Functor.Identity.runIdentity .) . mapAccumStoichiometricModelM -- | A stoichiometric model; a sparse matrix of stoichiometric coefficients by chemical reaction and species indices, along with sets of intermediate and reagent/product indices, where: -- * @i@ is the type of chemical reaction indices . -- -- * @a@ is the type of chemical species. -- data Sparse i a = Sparse { _sparseStoichiometry :: Map i (Map a StoichiometricCoefficient) , _sparseIntermediate :: Set a , _sparseReagentProduct :: Set a } deriving (Eq, Ord, Read, Show) Control.Lens.makeLenses ''Sparse instance (Ord i, Ord a) => Monoid (Sparse i a) where mempty = Sparse { _sparseStoichiometry = Data.Map.Strict.empty , _sparseIntermediate = Data.Set.empty , _sparseReagentProduct = Data.Set.empty } # INLINE mempty # mL `mappend` mR = Sparse { _sparseStoichiometry = Data.Map.Strict.unionWith (Data.Map.Strict.unionWith mappend) (_sparseStoichiometry mL) (_sparseStoichiometry mR) , _sparseIntermediate = Data.Set.union (_sparseIntermediate mL) (_sparseIntermediate mR) , _sparseReagentProduct = Data.Set.union (_sparseReagentProduct mL) (_sparseReagentProduct mR) } # INLINE mappend # instance (Ord i, Ord a) => MutableStoichiometricModel i a (Sparse i a) where modifyStoichiometricModelM ix0 = Control.Monad.Reader.Class.ask >>= assertStoichiometryM (\k x -> Control.Monad.State.Class.modify (assertStoichiometricCoefficient ix0 k x)) (\e -> Control.Monad.State.Class.modify (assertChemicalSpecies e)) where assertStoichiometricCoefficient :: (Ord i, Ord a) => i -> a -> StoichiometricCoefficient -> Sparse i a -> Sparse i a assertStoichiometricCoefficient ix k x = Control.Lens.over (sparseStoichiometry . Control.Lens.at ix) (Just . Control.Lens.over (Control.Lens.at k) (Just . mappend x . maybe mempty id) . maybe Data.Map.Strict.empty id) assertChemicalSpecies :: (Ord a) => Either a a -> Sparse i a -> Sparse i a assertChemicalSpecies = either (Control.Lens.over sparseIntermediate . Data.Set.insert) (Control.Lens.over sparseReagentProduct . Data.Set.insert) -- | A stoichiometric model; a pair of dense matrices of stoichiometric coefficients by chemical reaction index and chemical species, where: -- * @i@ is the type of chemical reaction indices . -- -- * @a@ is the type of chemical species. -- * is the type of matrix elements . -- data Dense i a e = Dense { _denseReactionIndices :: Set i , _denseIntermediate :: (Set a, Matrix e) ^ Dimension @a><i@ , where @a@ is the number of chemical species , and @i@ is the number of chemical reaction indices . , _denseReagentProduct :: (Set a, Matrix e) ^ Dimension @a><i@ , where @a@ is the number of chemical species , and @i@ is the number of chemical reaction indices . } deriving (Read, Show) deriving instance (Eq i, Eq a, Container Vector e, Num e) => Eq (Dense i a e) -- Control.Lens.makeLenses ''Dense | Converts a ' ' stoichiometric model to a ' Dense ' stoichiometric model . sparseToDense :: (Ord i, Ord a, Container Vector e, Fractional e) => Sparse i a -> Dense i a e sparseToDense = liftA3 (\mm -> Dense (Data.Map.Strict.keysSet mm) `on` liftA2 (,) id (mkMatrix mm)) _sparseStoichiometry _sparseIntermediate _sparseReagentProduct where -- | The 'mkMatrix' function constructs a matrix for the specified chemical species indices. mkMatrix :: (Ord i, Ord a, Container Vector e, Fractional e) => Map i (Map a StoichiometricCoefficient) -> Set a -> Matrix e mkMatrix mm ks = ( ks > < Data.Map.Strict.size mm ) $ do -- k <- Data.Set.toAscList ks -- m <- Data.Map.Strict.elems mm -- let x = Data . Map . Strict.findWithDefault k m -- x' = fromRational (getSum (getStoichiometricCoefficient x)) -- return x' mkMatrix mm ks = Numeric.LinearAlgebra.HMatrix.assoc (Data.Set.size ks, Data.Map.Strict.size mm) 0 $ catMaybes $ do ~(i, k) <- zip (enumFromThen 0 1) (Data.Set.toAscList ks) ~(j, m) <- zip (enumFromThen 0 1) (Data.Map.Strict.elems mm) return (fmap (\(StoichiometricCoefficient (Sum x)) -> ((i, j), fromRational x)) (Data.Map.Strict.lookup k m))
null
https://raw.githubusercontent.com/EMSL-NMR-EPR/Haskell-MFAPipe-Executable/8a7fd13202d3b6b7380af52d86e851e995a9b53e/MFAPipe/src/Science/Chemistry/Stoichiometry.hs
haskell
--------------------------------------------------------------------------- | Module : Science.Chemistry.Stoichiometry License : ECL-2.0 (see the LICENSE file in the distribution) Maintainer : Stability : experimental Portability : portable This module exports classes and types for the construction of sparse and dense stoichiometric models, including stoichiometry matrices. --------------------------------------------------------------------------- ** Conversion * Utility functions * @a@ is the type of chemical species; and, * @r@ is the type of the environment. ^ Assert chemical species, where 'Left' and 'Right' denote, respectively, intermediates and reagents/products. ^ Environment * @a@ is the type of chemical species; and, * @s@ is the type of the state of the stoichiometric model. | The 'mapAccumStoichiometricModelM' applies 'modifyStoichiometricModelM' to each element of a structure, passing the accumulated stoichiometric model from left to right. | The 'mapAccumStoichiometricModel' applies 'modifyStoichiometricModel' to each element of a structure, passing the accumulated stoichiometric model from left to right. | A stoichiometric model; a sparse matrix of stoichiometric coefficients by chemical reaction and species indices, along with sets of intermediate and reagent/product indices, where: * @a@ is the type of chemical species. | A stoichiometric model; a pair of dense matrices of stoichiometric coefficients by chemical reaction index and chemical species, where: * @a@ is the type of chemical species. Control.Lens.makeLenses ''Dense | The 'mkMatrix' function constructs a matrix for the specified chemical species indices. k <- Data.Set.toAscList ks m <- Data.Map.Strict.elems mm let x' = fromRational (getSum (getStoichiometricCoefficient x)) return x'
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # Copyright : 2016 - 17 Pacific Northwest National Laboratory module Science.Chemistry.Stoichiometry * HasStoichiometry class HasStoichiometry(..) * MutableStoichiometricModel class , MutableStoichiometricModel(..) , modifyStoichiometricModel * models , Sparse(..) , Dense(..) , sparseToDense , mapAccumStoichiometricModelM , mapAccumStoichiometricModel ) where import Control.Applicative (liftA2, liftA3) import qualified Control.Lens import Control.Monad.Reader.Class (MonadReader()) import qualified Control.Monad.Reader.Class import Control.Monad.State.Class (MonadState()) import qualified Control.Monad.State.Class import qualified Control.Monad.Trans.Reader import qualified Control.Monad.Trans.State.Strict as Control.Monad.Trans.State import Data.Function (on) import qualified Data.Functor.Identity import Data.Map.Strict (Map) import qualified Data.Map.Strict import Data.Maybe (catMaybes) import Data.Monoid (Sum(..)) import Data.Set (Set) import qualified Data.Set import Numeric.LinearAlgebra.HMatrix (Container(), Matrix, Vector) import qualified Numeric.LinearAlgebra.HMatrix import Science.Chemistry.Types | The ' HasStoichiometry ' class is used for types that have stoichiometry , where : class (Ord a) => HasStoichiometry a r | r -> a where # MINIMAL assertStoichiometryM # | @assertStoichiometryM f g r@ is a computation that asserts the stoichiometry of @r@ , given the functions @f@ and @g@ , in the context of an arbitrary ' Monad ' . assertStoichiometryM :: (Monad m) => (a -> StoichiometricCoefficient -> m ()) ^ Assert chemical species with ' StoichiometricCoefficient ' . -> (Either a a -> m ()) -> r -> m () | The ' MutableStoichiometricModel ' class is used for types that are mutable stoichiometric models , where : * @i@ is the type of chemical reaction indices ; class (Ord i, Ord a) => MutableStoichiometricModel i a s | s -> i, s -> a where # MINIMAL modifyStoichiometricModelM # | @modifyStoichiometricModelM i@ is a computation that modifies the current state of a stoichiometric model . modifyStoichiometricModelM :: (MonadReader r m, MonadState s m, HasStoichiometry a r) => i -> m () | @modifyStoichiometricModel i r s@ is a computation that modifies the current state of the stoichiometric model @s@ , given the environment @r@. modifyStoichiometricModel :: (HasStoichiometry a r, MutableStoichiometricModel i a s) => i -> r -> s -> s modifyStoichiometricModel ix r = Data.Functor.Identity.runIdentity . Control.Monad.Trans.State.execStateT (Control.Monad.Trans.Reader.runReaderT (modifyStoichiometricModelM ix) r) mapAccumStoichiometricModelM :: (Foldable f, Monad m, HasStoichiometry a r, MutableStoichiometricModel i a s) => f (i, r) -> s -> m s mapAccumStoichiometricModelM = Control.Monad.Trans.State.execStateT . mapM_ (uncurry (\ix r -> Control.Monad.Trans.Reader.runReaderT (modifyStoichiometricModelM ix) r)) mapAccumStoichiometricModel :: (Foldable f, HasStoichiometry a r, MutableStoichiometricModel i a s) => f (i, r) -> s -> s mapAccumStoichiometricModel = (Data.Functor.Identity.runIdentity .) . mapAccumStoichiometricModelM * @i@ is the type of chemical reaction indices . data Sparse i a = Sparse { _sparseStoichiometry :: Map i (Map a StoichiometricCoefficient) , _sparseIntermediate :: Set a , _sparseReagentProduct :: Set a } deriving (Eq, Ord, Read, Show) Control.Lens.makeLenses ''Sparse instance (Ord i, Ord a) => Monoid (Sparse i a) where mempty = Sparse { _sparseStoichiometry = Data.Map.Strict.empty , _sparseIntermediate = Data.Set.empty , _sparseReagentProduct = Data.Set.empty } # INLINE mempty # mL `mappend` mR = Sparse { _sparseStoichiometry = Data.Map.Strict.unionWith (Data.Map.Strict.unionWith mappend) (_sparseStoichiometry mL) (_sparseStoichiometry mR) , _sparseIntermediate = Data.Set.union (_sparseIntermediate mL) (_sparseIntermediate mR) , _sparseReagentProduct = Data.Set.union (_sparseReagentProduct mL) (_sparseReagentProduct mR) } # INLINE mappend # instance (Ord i, Ord a) => MutableStoichiometricModel i a (Sparse i a) where modifyStoichiometricModelM ix0 = Control.Monad.Reader.Class.ask >>= assertStoichiometryM (\k x -> Control.Monad.State.Class.modify (assertStoichiometricCoefficient ix0 k x)) (\e -> Control.Monad.State.Class.modify (assertChemicalSpecies e)) where assertStoichiometricCoefficient :: (Ord i, Ord a) => i -> a -> StoichiometricCoefficient -> Sparse i a -> Sparse i a assertStoichiometricCoefficient ix k x = Control.Lens.over (sparseStoichiometry . Control.Lens.at ix) (Just . Control.Lens.over (Control.Lens.at k) (Just . mappend x . maybe mempty id) . maybe Data.Map.Strict.empty id) assertChemicalSpecies :: (Ord a) => Either a a -> Sparse i a -> Sparse i a assertChemicalSpecies = either (Control.Lens.over sparseIntermediate . Data.Set.insert) (Control.Lens.over sparseReagentProduct . Data.Set.insert) * @i@ is the type of chemical reaction indices . * is the type of matrix elements . data Dense i a e = Dense { _denseReactionIndices :: Set i , _denseIntermediate :: (Set a, Matrix e) ^ Dimension @a><i@ , where @a@ is the number of chemical species , and @i@ is the number of chemical reaction indices . , _denseReagentProduct :: (Set a, Matrix e) ^ Dimension @a><i@ , where @a@ is the number of chemical species , and @i@ is the number of chemical reaction indices . } deriving (Read, Show) deriving instance (Eq i, Eq a, Container Vector e, Num e) => Eq (Dense i a e) | Converts a ' ' stoichiometric model to a ' Dense ' stoichiometric model . sparseToDense :: (Ord i, Ord a, Container Vector e, Fractional e) => Sparse i a -> Dense i a e sparseToDense = liftA3 (\mm -> Dense (Data.Map.Strict.keysSet mm) `on` liftA2 (,) id (mkMatrix mm)) _sparseStoichiometry _sparseIntermediate _sparseReagentProduct where mkMatrix :: (Ord i, Ord a, Container Vector e, Fractional e) => Map i (Map a StoichiometricCoefficient) -> Set a -> Matrix e mkMatrix mm ks = ( ks > < Data.Map.Strict.size mm ) $ do x = Data . Map . Strict.findWithDefault k m mkMatrix mm ks = Numeric.LinearAlgebra.HMatrix.assoc (Data.Set.size ks, Data.Map.Strict.size mm) 0 $ catMaybes $ do ~(i, k) <- zip (enumFromThen 0 1) (Data.Set.toAscList ks) ~(j, m) <- zip (enumFromThen 0 1) (Data.Map.Strict.elems mm) return (fmap (\(StoichiometricCoefficient (Sum x)) -> ((i, j), fromRational x)) (Data.Map.Strict.lookup k m))
23d3aeed00dd85324041df7276f9859f2497e023cde1ab85f8475de7f30c9f91
active-group/sqlosure
oracledb.clj
(ns sqlosure.backends.oracledb (:require [active.clojure.monad :as m] [sqlosure.backend :as backend] [sqlosure.sql-put :as sql-put])) TODO This is only a stub implementation . (defn oracledb-put-alias [alias] (if alias (sql-put/write! alias) (m/return nil))) (def oracledb-put-parameterization (sql-put/make-sql-put-parameterization oracledb-put-alias sql-put/default-put-combine)) (def implementation (-> backend/backend (backend/reify-put-parameterization oracledb-put-parameterization)))
null
https://raw.githubusercontent.com/active-group/sqlosure/3cd74e90df4f3c49c841a1a75941acc7444c4bfb/src/sqlosure/backends/oracledb.clj
clojure
(ns sqlosure.backends.oracledb (:require [active.clojure.monad :as m] [sqlosure.backend :as backend] [sqlosure.sql-put :as sql-put])) TODO This is only a stub implementation . (defn oracledb-put-alias [alias] (if alias (sql-put/write! alias) (m/return nil))) (def oracledb-put-parameterization (sql-put/make-sql-put-parameterization oracledb-put-alias sql-put/default-put-combine)) (def implementation (-> backend/backend (backend/reify-put-parameterization oracledb-put-parameterization)))
576eed263de91f04b96517c9d0813cdef4bad0a6c2d591e12980f0b3cf315aa4
typelead/etlas
Message.hs
{-# LANGUAGE BangPatterns #-} module Distribution.Solver.Modular.Message ( Message(..), showMessages ) where import qualified Data.List as L import Prelude hiding (pi) from Cabal import Distribution.Solver.Modular.Dependency import Distribution.Solver.Modular.Flag import Distribution.Solver.Modular.Package import Distribution.Solver.Modular.Tree ( FailReason(..), POption(..) ) import Distribution.Solver.Types.ConstraintSource import Distribution.Solver.Types.PackagePath import Distribution.Solver.Types.Progress data Message = Enter -- ^ increase indentation level | Leave -- ^ decrease indentation level | TryP QPN POption | TryF QFN Bool | TryS QSN Bool | Next (Goal QPN) | Success | Failure ConflictSet FailReason -- | Transforms the structured message type to actual messages (strings). -- -- Takes an additional relevance predicate. The predicate gets a stack of goal -- variables and can decide whether messages regarding these goals are relevant. -- You can plug in 'const True' if you're interested in a full trace. If you -- want a slice of the trace concerning a particular conflict set, then plug in -- a predicate returning 'True' on the empty stack and if the head is in the -- conflict set. -- The second argument indicates if the level numbers should be shown . This is -- recommended for any trace that involves backtracking, because only the level numbers will allow to keep track of backjumps . showMessages :: ([Var QPN] -> Bool) -> Bool -> Progress Message a b -> Progress String a b showMessages p sl = go [] 0 where -- The stack 'v' represents variables that are currently assigned by the -- solver. 'go' pushes a variable for a recursive call when it encounters ' TryP ' , ' TryF ' , or ' TryS ' and pops a variable when it encounters ' Leave ' . -- When 'go' processes a package goal, or a package goal followed by a -- 'Failure', it calls 'atLevel' with the goal variable at the head of the -- stack so that the predicate can also select messages relating to package -- goal choices. go :: [Var QPN] -> Int -> Progress Message a b -> Progress String a b go !_ !_ (Done x) = Done x go !_ !_ (Fail x) = Fail x -- complex patterns go !v !l (Step (TryP qpn i) (Step Enter (Step (Failure c fr) (Step Leave ms)))) = goPReject v l qpn [i] c fr ms go !v !l (Step (TryF qfn b) (Step Enter (Step (Failure c fr) (Step Leave ms)))) = (atLevel (add (F qfn) v) l $ "rejecting: " ++ showQFNBool qfn b ++ showFR c fr) (go v l ms) go !v !l (Step (TryS qsn b) (Step Enter (Step (Failure c fr) (Step Leave ms)))) = (atLevel (add (S qsn) v) l $ "rejecting: " ++ showQSNBool qsn b ++ showFR c fr) (go v l ms) go !v !l (Step (Next (Goal (P qpn) gr)) (Step (TryP qpn' i) ms@(Step Enter (Step (Next _) _)))) = (atLevel (add (P qpn) v) l $ "trying: " ++ showQPNPOpt qpn' i ++ showGR gr) (go (add (P qpn) v) l ms) go !v !l (Step (Next (Goal (P qpn) gr)) ms@(Fail _)) = (atLevel (add (P qpn) v) l $ "unknown package: " ++ showQPN qpn ++ showGR gr) $ go v l ms -- the previous case potentially arises in the error output, because we remove the backjump itself if we cut the log after the first error go !v !l (Step (Next (Goal (P qpn) gr)) ms@(Step (Failure _c Backjump) _)) = (atLevel (add (P qpn) v) l $ "unknown package: " ++ showQPN qpn ++ showGR gr) $ go v l ms go !v !l (Step (Next (Goal (P qpn) gr)) (Step (Failure c fr) ms)) = let v' = add (P qpn) v in (atLevel v' l $ showPackageGoal qpn gr) $ (atLevel v' l $ showFailure c fr) (go v l ms) go !v !l (Step (Failure c Backjump) ms@(Step Leave (Step (Failure c' Backjump) _))) | c == c' = go v l ms -- standard display go !v !l (Step Enter ms) = go v (l+1) ms go !v !l (Step Leave ms) = go (drop 1 v) (l-1) ms go !v !l (Step (TryP qpn i) ms) = (atLevel (add (P qpn) v) l $ "trying: " ++ showQPNPOpt qpn i) (go (add (P qpn) v) l ms) go !v !l (Step (TryF qfn b) ms) = (atLevel (add (F qfn) v) l $ "trying: " ++ showQFNBool qfn b) (go (add (F qfn) v) l ms) go !v !l (Step (TryS qsn b) ms) = (atLevel (add (S qsn) v) l $ "trying: " ++ showQSNBool qsn b) (go (add (S qsn) v) l ms) go !v !l (Step (Next (Goal (P qpn) gr)) ms) = (atLevel (add (P qpn) v) l $ showPackageGoal qpn gr) (go v l ms) go !v !l (Step (Next _) ms) = go v l ms -- ignore flag goals in the log go !v !l (Step (Success) ms) = (atLevel v l $ "done") (go v l ms) go !v !l (Step (Failure c fr) ms) = (atLevel v l $ showFailure c fr) (go v l ms) showPackageGoal :: QPN -> QGoalReason -> String showPackageGoal qpn gr = "next goal: " ++ showQPN qpn ++ showGR gr showFailure :: ConflictSet -> FailReason -> String showFailure c fr = "fail" ++ showFR c fr add :: Var QPN -> [Var QPN] -> [Var QPN] add v vs = simplifyVar v : vs -- special handler for many subsequent package rejections goPReject :: [Var QPN] -> Int -> QPN -> [POption] -> ConflictSet -> FailReason -> Progress Message a b -> Progress String a b goPReject v l qpn is c fr (Step (TryP qpn' i) (Step Enter (Step (Failure _ fr') (Step Leave ms)))) | qpn == qpn' && fr == fr' = goPReject v l qpn (i : is) c fr ms goPReject v l qpn is c fr ms = (atLevel (P qpn : v) l $ "rejecting: " ++ L.intercalate ", " (map (showQPNPOpt qpn) (reverse is)) ++ showFR c fr) (go v l ms) -- write a message, but only if it's relevant; we can also enable or disable the display of the current level atLevel :: [Var QPN] -> Int -> String -> Progress String a b -> Progress String a b atLevel v l x xs | sl && p v = let s = show l in Step ("[" ++ replicate (3 - length s) '_' ++ s ++ "] " ++ x) xs | p v = Step x xs | otherwise = xs showQPNPOpt :: QPN -> POption -> String showQPNPOpt qpn@(Q _pp pn) (POption i linkedTo) = case linkedTo of Consistent with prior to POption Just pp' -> showQPN qpn ++ "~>" ++ showPI (PI (Q pp' pn) i) showGR :: QGoalReason -> String showGR UserGoal = " (user goal)" showGR (PDependency pi) = " (dependency of " ++ showPI pi ++ ")" showGR (FDependency qfn b) = " (dependency of " ++ showQFNBool qfn b ++ ")" showGR (SDependency qsn) = " (dependency of " ++ showQSNBool qsn True ++ ")" showFR :: ConflictSet -> FailReason -> String showFR _ InconsistentInitialConstraints = " (inconsistent initial constraints)" showFR _ (Conflicting ds) = " (conflict: " ++ L.intercalate ", " (map showDep ds) ++ ")" showFR _ CannotInstall = " (only already installed instances can be used)" showFR _ CannotReinstall = " (avoiding to reinstall a package with same version but new dependencies)" showFR _ Shadowed = " (shadowed by another installed package with same version)" showFR _ Broken = " (package is broken)" showFR _ (GlobalConstraintVersion vr src) = " (" ++ constraintSource src ++ " requires " ++ display vr ++ ")" showFR _ (GlobalConstraintInstalled src) = " (" ++ constraintSource src ++ " requires installed instance)" showFR _ (GlobalConstraintSource src) = " (" ++ constraintSource src ++ " requires source instance)" showFR _ (GlobalConstraintFlag src) = " (" ++ constraintSource src ++ " requires opposite flag selection)" showFR _ ManualFlag = " (manual flag can only be changed explicitly)" showFR c Backjump = " (backjumping, conflict set: " ++ showConflictSet c ++ ")" showFR _ MultipleInstances = " (multiple instances)" showFR c (DependenciesNotLinked msg) = " (dependencies not linked: " ++ msg ++ "; conflict set: " ++ showConflictSet c ++ ")" showFR c CyclicDependencies = " (cyclic dependencies; conflict set: " ++ showConflictSet c ++ ")" -- The following are internal failures. They should not occur. In the -- interest of not crashing unnecessarily, we still just print an error -- message though. showFR _ (MalformedFlagChoice qfn) = " (INTERNAL ERROR: MALFORMED FLAG CHOICE: " ++ showQFN qfn ++ ")" showFR _ (MalformedStanzaChoice qsn) = " (INTERNAL ERROR: MALFORMED STANZA CHOICE: " ++ showQSN qsn ++ ")" showFR _ EmptyGoalChoice = " (INTERNAL ERROR: EMPTY GOAL CHOICE)" constraintSource :: ConstraintSource -> String constraintSource src = "constraint from " ++ showConstraintSource src
null
https://raw.githubusercontent.com/typelead/etlas/bbd7c558169e1fda086e759e1a6f8c8ca2807583/etlas/Distribution/Solver/Modular/Message.hs
haskell
# LANGUAGE BangPatterns # ^ increase indentation level ^ decrease indentation level | Transforms the structured message type to actual messages (strings). Takes an additional relevance predicate. The predicate gets a stack of goal variables and can decide whether messages regarding these goals are relevant. You can plug in 'const True' if you're interested in a full trace. If you want a slice of the trace concerning a particular conflict set, then plug in a predicate returning 'True' on the empty stack and if the head is in the conflict set. recommended for any trace that involves backtracking, because only the level The stack 'v' represents variables that are currently assigned by the solver. 'go' pushes a variable for a recursive call when it encounters When 'go' processes a package goal, or a package goal followed by a 'Failure', it calls 'atLevel' with the goal variable at the head of the stack so that the predicate can also select messages relating to package goal choices. complex patterns the previous case potentially arises in the error output, because we remove the backjump itself standard display ignore flag goals in the log special handler for many subsequent package rejections write a message, but only if it's relevant; we can also enable or disable the display of the current level The following are internal failures. They should not occur. In the interest of not crashing unnecessarily, we still just print an error message though.
module Distribution.Solver.Modular.Message ( Message(..), showMessages ) where import qualified Data.List as L import Prelude hiding (pi) from Cabal import Distribution.Solver.Modular.Dependency import Distribution.Solver.Modular.Flag import Distribution.Solver.Modular.Package import Distribution.Solver.Modular.Tree ( FailReason(..), POption(..) ) import Distribution.Solver.Types.ConstraintSource import Distribution.Solver.Types.PackagePath import Distribution.Solver.Types.Progress data Message = | TryP QPN POption | TryF QFN Bool | TryS QSN Bool | Next (Goal QPN) | Success | Failure ConflictSet FailReason The second argument indicates if the level numbers should be shown . This is numbers will allow to keep track of backjumps . showMessages :: ([Var QPN] -> Bool) -> Bool -> Progress Message a b -> Progress String a b showMessages p sl = go [] 0 where ' TryP ' , ' TryF ' , or ' TryS ' and pops a variable when it encounters ' Leave ' . go :: [Var QPN] -> Int -> Progress Message a b -> Progress String a b go !_ !_ (Done x) = Done x go !_ !_ (Fail x) = Fail x go !v !l (Step (TryP qpn i) (Step Enter (Step (Failure c fr) (Step Leave ms)))) = goPReject v l qpn [i] c fr ms go !v !l (Step (TryF qfn b) (Step Enter (Step (Failure c fr) (Step Leave ms)))) = (atLevel (add (F qfn) v) l $ "rejecting: " ++ showQFNBool qfn b ++ showFR c fr) (go v l ms) go !v !l (Step (TryS qsn b) (Step Enter (Step (Failure c fr) (Step Leave ms)))) = (atLevel (add (S qsn) v) l $ "rejecting: " ++ showQSNBool qsn b ++ showFR c fr) (go v l ms) go !v !l (Step (Next (Goal (P qpn) gr)) (Step (TryP qpn' i) ms@(Step Enter (Step (Next _) _)))) = (atLevel (add (P qpn) v) l $ "trying: " ++ showQPNPOpt qpn' i ++ showGR gr) (go (add (P qpn) v) l ms) go !v !l (Step (Next (Goal (P qpn) gr)) ms@(Fail _)) = (atLevel (add (P qpn) v) l $ "unknown package: " ++ showQPN qpn ++ showGR gr) $ go v l ms if we cut the log after the first error go !v !l (Step (Next (Goal (P qpn) gr)) ms@(Step (Failure _c Backjump) _)) = (atLevel (add (P qpn) v) l $ "unknown package: " ++ showQPN qpn ++ showGR gr) $ go v l ms go !v !l (Step (Next (Goal (P qpn) gr)) (Step (Failure c fr) ms)) = let v' = add (P qpn) v in (atLevel v' l $ showPackageGoal qpn gr) $ (atLevel v' l $ showFailure c fr) (go v l ms) go !v !l (Step (Failure c Backjump) ms@(Step Leave (Step (Failure c' Backjump) _))) | c == c' = go v l ms go !v !l (Step Enter ms) = go v (l+1) ms go !v !l (Step Leave ms) = go (drop 1 v) (l-1) ms go !v !l (Step (TryP qpn i) ms) = (atLevel (add (P qpn) v) l $ "trying: " ++ showQPNPOpt qpn i) (go (add (P qpn) v) l ms) go !v !l (Step (TryF qfn b) ms) = (atLevel (add (F qfn) v) l $ "trying: " ++ showQFNBool qfn b) (go (add (F qfn) v) l ms) go !v !l (Step (TryS qsn b) ms) = (atLevel (add (S qsn) v) l $ "trying: " ++ showQSNBool qsn b) (go (add (S qsn) v) l ms) go !v !l (Step (Next (Goal (P qpn) gr)) ms) = (atLevel (add (P qpn) v) l $ showPackageGoal qpn gr) (go v l ms) go !v !l (Step (Success) ms) = (atLevel v l $ "done") (go v l ms) go !v !l (Step (Failure c fr) ms) = (atLevel v l $ showFailure c fr) (go v l ms) showPackageGoal :: QPN -> QGoalReason -> String showPackageGoal qpn gr = "next goal: " ++ showQPN qpn ++ showGR gr showFailure :: ConflictSet -> FailReason -> String showFailure c fr = "fail" ++ showFR c fr add :: Var QPN -> [Var QPN] -> [Var QPN] add v vs = simplifyVar v : vs goPReject :: [Var QPN] -> Int -> QPN -> [POption] -> ConflictSet -> FailReason -> Progress Message a b -> Progress String a b goPReject v l qpn is c fr (Step (TryP qpn' i) (Step Enter (Step (Failure _ fr') (Step Leave ms)))) | qpn == qpn' && fr == fr' = goPReject v l qpn (i : is) c fr ms goPReject v l qpn is c fr ms = (atLevel (P qpn : v) l $ "rejecting: " ++ L.intercalate ", " (map (showQPNPOpt qpn) (reverse is)) ++ showFR c fr) (go v l ms) atLevel :: [Var QPN] -> Int -> String -> Progress String a b -> Progress String a b atLevel v l x xs | sl && p v = let s = show l in Step ("[" ++ replicate (3 - length s) '_' ++ s ++ "] " ++ x) xs | p v = Step x xs | otherwise = xs showQPNPOpt :: QPN -> POption -> String showQPNPOpt qpn@(Q _pp pn) (POption i linkedTo) = case linkedTo of Consistent with prior to POption Just pp' -> showQPN qpn ++ "~>" ++ showPI (PI (Q pp' pn) i) showGR :: QGoalReason -> String showGR UserGoal = " (user goal)" showGR (PDependency pi) = " (dependency of " ++ showPI pi ++ ")" showGR (FDependency qfn b) = " (dependency of " ++ showQFNBool qfn b ++ ")" showGR (SDependency qsn) = " (dependency of " ++ showQSNBool qsn True ++ ")" showFR :: ConflictSet -> FailReason -> String showFR _ InconsistentInitialConstraints = " (inconsistent initial constraints)" showFR _ (Conflicting ds) = " (conflict: " ++ L.intercalate ", " (map showDep ds) ++ ")" showFR _ CannotInstall = " (only already installed instances can be used)" showFR _ CannotReinstall = " (avoiding to reinstall a package with same version but new dependencies)" showFR _ Shadowed = " (shadowed by another installed package with same version)" showFR _ Broken = " (package is broken)" showFR _ (GlobalConstraintVersion vr src) = " (" ++ constraintSource src ++ " requires " ++ display vr ++ ")" showFR _ (GlobalConstraintInstalled src) = " (" ++ constraintSource src ++ " requires installed instance)" showFR _ (GlobalConstraintSource src) = " (" ++ constraintSource src ++ " requires source instance)" showFR _ (GlobalConstraintFlag src) = " (" ++ constraintSource src ++ " requires opposite flag selection)" showFR _ ManualFlag = " (manual flag can only be changed explicitly)" showFR c Backjump = " (backjumping, conflict set: " ++ showConflictSet c ++ ")" showFR _ MultipleInstances = " (multiple instances)" showFR c (DependenciesNotLinked msg) = " (dependencies not linked: " ++ msg ++ "; conflict set: " ++ showConflictSet c ++ ")" showFR c CyclicDependencies = " (cyclic dependencies; conflict set: " ++ showConflictSet c ++ ")" showFR _ (MalformedFlagChoice qfn) = " (INTERNAL ERROR: MALFORMED FLAG CHOICE: " ++ showQFN qfn ++ ")" showFR _ (MalformedStanzaChoice qsn) = " (INTERNAL ERROR: MALFORMED STANZA CHOICE: " ++ showQSN qsn ++ ")" showFR _ EmptyGoalChoice = " (INTERNAL ERROR: EMPTY GOAL CHOICE)" constraintSource :: ConstraintSource -> String constraintSource src = "constraint from " ++ showConstraintSource src
c781ac5ac10072ec06659e2482cfc89ef4d4fa75ec626c1fdd2cf0ad6c3c0788
shirok/Gauche
chibi-test.scm
;; A quick hack to run test suite written for ;; (define-module compat.chibi-test (use gauche.test) (use util.match) (export chibi-test current-test-comparator)) (select-module compat.chibi-test) (define current-test-comparator (make-parameter equal?)) (define-syntax gauche:parameterize parameterize) (define gauche:test-error test-error) chibi allows internal defines to interleave expressions . Gauche ca n't ;; do that, so we translate the whole body of chibi-test into ;; nested lets. ;; we also cheat the scope - we want to replace macros such as ;; test, include and parameterize, but we want them to be effective ;; only inside chibi-test. (define-syntax chibi-test (er-macro-transformer (^[f r c] `(let-syntax ([parameterize (syntax-rules () [(_ bindings . fs) (,(r'gauche:parameterize) bindings (,(r'chibi-test:expand) fs))])] [use NB : We ignore ' use ' in the chibi test file ; necessary modules ;; are supposed to be already used in the includer. (syntax-rules () [(_ . args) (begin)])] [import ;; So as import (syntax-rules () [(_ . args) (begin)])] [include (syntax-rules () [(_ file) (,(r'chibi-test:include) file)])] [test (syntax-rules () [(_ name expected expr) (,(r'test*) name expected expr (current-test-comparator))] [(_ expected expr) (,(r'test*) 'expr expected expr (current-test-comparator))])] [test-group (syntax-rules () [(_ name . fs) (begin (,(r'test-section) name) (,(r'chibi-test:expand) fs))])] [test-assert (syntax-rules () [(_ expr) (,(r'test*) 'expr #t (,(r'boolean) expr))] [(_ name expr) (,(r'test*) name #t (,(r'boolean) expr))])] [test-equal (syntax-rules () [(_ equal name expect expr) (,(r'parameterize) ((current-test-comparator equal)) (,(r'test*) name expect expr))] [(_ equal expect expr) (,(r'parameterize) ((current-test-comparator equal)) (,(r'test*) 'expr expect expr))])] [test-not (syntax-rules () [(_ expr) (,(r'test*) 'expr #f (,(r'boolean) expr))] [(_ name expr) (,(r'test*) name #f (,(r'boolean) expr))])] [test-error (syntax-rules () [(_ expr) (,(r'test*) 'expr (,(r'gauche:test-error)) expr)])] [test-exit ;; ignore test-exit, for it is inside chibi-test and we don't ;; want to exit. (syntax-rules () [(_ . args) (begin)])] ) (,(r'chibi-test:expand) ,(cdr f)))))) ;; We gather definitions at the same level, so that mutually recursive ;; definitions work (define-syntax chibi-test:expand (er-macro-transformer (^[f r c] (let loop ([forms (cadr f)] [defs '()]) (match forms [() (if (null? defs) (quasirename r `(begin)) (quasirename r `(let () ,@(reverse defs) (begin))))] [(form) (if (null? defs) (car forms) (quasirename r `(let () ,@(reverse defs) ,(car forms))))] [((and ((? (cut c <> (r'define))) . _) def) . forms) (loop forms (cons def defs))] [(form . forms) (if (null? defs) (quasirename r `(let () ,form (chibi-test:expand ,forms))) (quasirename r `(let () ,@(reverse defs) ,form (chibi-test:expand ,forms))))]))))) (define-syntax chibi-test:include (er-macro-transformer (^[f r c] (let ([file (cadr f)]) (let1 iport ((with-module gauche.internal pass1/open-include-file) file (current-load-path)) (unwind-protect `(,(r 'chibi-test:expand) ,(port->sexp-list iport)) (close-port iport))))))) A hack to make Gauche think it has loaded chibi.test so that it wo n't ;; tripped by (import (chibi test)) in the test code. (define-module chibi.test (extend compat.chibi-test)) (provide "chibi/test") (provide "compat/chibi-test")
null
https://raw.githubusercontent.com/shirok/Gauche/a41f073942a282e68c1559474f369021ed4533bc/lib/compat/chibi-test.scm
scheme
do that, so we translate the whole body of chibi-test into nested lets. we also cheat the scope - we want to replace macros such as test, include and parameterize, but we want them to be effective only inside chibi-test. necessary modules are supposed to be already used in the includer. So as import ignore test-exit, for it is inside chibi-test and we don't want to exit. We gather definitions at the same level, so that mutually recursive definitions work tripped by (import (chibi test)) in the test code.
A quick hack to run test suite written for (define-module compat.chibi-test (use gauche.test) (use util.match) (export chibi-test current-test-comparator)) (select-module compat.chibi-test) (define current-test-comparator (make-parameter equal?)) (define-syntax gauche:parameterize parameterize) (define gauche:test-error test-error) chibi allows internal defines to interleave expressions . Gauche ca n't (define-syntax chibi-test (er-macro-transformer (^[f r c] `(let-syntax ([parameterize (syntax-rules () [(_ bindings . fs) (,(r'gauche:parameterize) bindings (,(r'chibi-test:expand) fs))])] [use (syntax-rules () [(_ . args) (begin)])] [import (syntax-rules () [(_ . args) (begin)])] [include (syntax-rules () [(_ file) (,(r'chibi-test:include) file)])] [test (syntax-rules () [(_ name expected expr) (,(r'test*) name expected expr (current-test-comparator))] [(_ expected expr) (,(r'test*) 'expr expected expr (current-test-comparator))])] [test-group (syntax-rules () [(_ name . fs) (begin (,(r'test-section) name) (,(r'chibi-test:expand) fs))])] [test-assert (syntax-rules () [(_ expr) (,(r'test*) 'expr #t (,(r'boolean) expr))] [(_ name expr) (,(r'test*) name #t (,(r'boolean) expr))])] [test-equal (syntax-rules () [(_ equal name expect expr) (,(r'parameterize) ((current-test-comparator equal)) (,(r'test*) name expect expr))] [(_ equal expect expr) (,(r'parameterize) ((current-test-comparator equal)) (,(r'test*) 'expr expect expr))])] [test-not (syntax-rules () [(_ expr) (,(r'test*) 'expr #f (,(r'boolean) expr))] [(_ name expr) (,(r'test*) name #f (,(r'boolean) expr))])] [test-error (syntax-rules () [(_ expr) (,(r'test*) 'expr (,(r'gauche:test-error)) expr)])] [test-exit (syntax-rules () [(_ . args) (begin)])] ) (,(r'chibi-test:expand) ,(cdr f)))))) (define-syntax chibi-test:expand (er-macro-transformer (^[f r c] (let loop ([forms (cadr f)] [defs '()]) (match forms [() (if (null? defs) (quasirename r `(begin)) (quasirename r `(let () ,@(reverse defs) (begin))))] [(form) (if (null? defs) (car forms) (quasirename r `(let () ,@(reverse defs) ,(car forms))))] [((and ((? (cut c <> (r'define))) . _) def) . forms) (loop forms (cons def defs))] [(form . forms) (if (null? defs) (quasirename r `(let () ,form (chibi-test:expand ,forms))) (quasirename r `(let () ,@(reverse defs) ,form (chibi-test:expand ,forms))))]))))) (define-syntax chibi-test:include (er-macro-transformer (^[f r c] (let ([file (cadr f)]) (let1 iport ((with-module gauche.internal pass1/open-include-file) file (current-load-path)) (unwind-protect `(,(r 'chibi-test:expand) ,(port->sexp-list iport)) (close-port iport))))))) A hack to make Gauche think it has loaded chibi.test so that it wo n't (define-module chibi.test (extend compat.chibi-test)) (provide "chibi/test") (provide "compat/chibi-test")
339f09a0ef4c51c3effde1c59d0668c469455e3286ae5f356c43618863ee412f
zarkone/stumpwm.d
package.lisp
package.lisp (defpackage #:wifi (:use #:cl :common-lisp :stumpwm ) (:export #:*iwconfig-path* #:*wireless-device*))
null
https://raw.githubusercontent.com/zarkone/stumpwm.d/021e51c98a80783df1345826ac9390b44a7d0aae/modules/modeline/wifi/package.lisp
lisp
package.lisp (defpackage #:wifi (:use #:cl :common-lisp :stumpwm ) (:export #:*iwconfig-path* #:*wireless-device*))
139430e22d2770c43ecddbf24d9a4e945d950696383acc6dd4caafed0d7116be
spawnfest/eep49ers
wxNotifyEvent.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 2020 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% This file is generated DO NOT EDIT -module(wxNotifyEvent). -include("wxe.hrl"). -export([allow/1,isAllowed/1,veto/1]). %% inherited exports -export([getClientData/1,getExtraLong/1,getId/1,getInt/1,getSelection/1,getSkipped/1, getString/1,getTimestamp/1,isChecked/1,isCommandEvent/1,isSelection/1, parent_class/1,resumePropagation/2,setInt/2,setString/2,shouldPropagate/1, skip/1,skip/2,stopPropagation/1]). -type wxNotifyEvent() :: wx:wx_object(). -export_type([wxNotifyEvent/0]). %% @hidden parent_class(wxCommandEvent) -> true; parent_class(wxEvent) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). %% @doc See <a href="#wxnotifyeventallow">external documentation</a>. -spec allow(This) -> 'ok' when This::wxNotifyEvent(). allow(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxNotifyEvent), wxe_util:queue_cmd(This,?get_env(),?wxNotifyEvent_Allow). %% @doc See <a href="#wxnotifyeventisallowed">external documentation</a>. -spec isAllowed(This) -> boolean() when This::wxNotifyEvent(). isAllowed(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxNotifyEvent), wxe_util:queue_cmd(This,?get_env(),?wxNotifyEvent_IsAllowed), wxe_util:rec(?wxNotifyEvent_IsAllowed). %% @doc See <a href="#wxnotifyeventveto">external documentation</a>. -spec veto(This) -> 'ok' when This::wxNotifyEvent(). veto(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxNotifyEvent), wxe_util:queue_cmd(This,?get_env(),?wxNotifyEvent_Veto). %% From wxCommandEvent %% @hidden setString(This,String) -> wxCommandEvent:setString(This,String). %% @hidden setInt(This,IntCommand) -> wxCommandEvent:setInt(This,IntCommand). %% @hidden isSelection(This) -> wxCommandEvent:isSelection(This). %% @hidden isChecked(This) -> wxCommandEvent:isChecked(This). %% @hidden getString(This) -> wxCommandEvent:getString(This). %% @hidden getSelection(This) -> wxCommandEvent:getSelection(This). %% @hidden getInt(This) -> wxCommandEvent:getInt(This). %% @hidden getExtraLong(This) -> wxCommandEvent:getExtraLong(This). %% @hidden getClientData(This) -> wxCommandEvent:getClientData(This). %% From wxEvent %% @hidden stopPropagation(This) -> wxEvent:stopPropagation(This). %% @hidden skip(This, Options) -> wxEvent:skip(This, Options). %% @hidden skip(This) -> wxEvent:skip(This). %% @hidden shouldPropagate(This) -> wxEvent:shouldPropagate(This). %% @hidden resumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel). %% @hidden isCommandEvent(This) -> wxEvent:isCommandEvent(This). %% @hidden getTimestamp(This) -> wxEvent:getTimestamp(This). %% @hidden getSkipped(This) -> wxEvent:getSkipped(This). %% @hidden getId(This) -> wxEvent:getId(This).
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/wx/src/gen/wxNotifyEvent.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% This file is generated DO NOT EDIT inherited exports @hidden @doc See <a href="#wxnotifyeventallow">external documentation</a>. @doc See <a href="#wxnotifyeventisallowed">external documentation</a>. @doc See <a href="#wxnotifyeventveto">external documentation</a>. From wxCommandEvent @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden From wxEvent @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden
Copyright Ericsson AB 2008 - 2020 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(wxNotifyEvent). -include("wxe.hrl"). -export([allow/1,isAllowed/1,veto/1]). -export([getClientData/1,getExtraLong/1,getId/1,getInt/1,getSelection/1,getSkipped/1, getString/1,getTimestamp/1,isChecked/1,isCommandEvent/1,isSelection/1, parent_class/1,resumePropagation/2,setInt/2,setString/2,shouldPropagate/1, skip/1,skip/2,stopPropagation/1]). -type wxNotifyEvent() :: wx:wx_object(). -export_type([wxNotifyEvent/0]). parent_class(wxCommandEvent) -> true; parent_class(wxEvent) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). -spec allow(This) -> 'ok' when This::wxNotifyEvent(). allow(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxNotifyEvent), wxe_util:queue_cmd(This,?get_env(),?wxNotifyEvent_Allow). -spec isAllowed(This) -> boolean() when This::wxNotifyEvent(). isAllowed(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxNotifyEvent), wxe_util:queue_cmd(This,?get_env(),?wxNotifyEvent_IsAllowed), wxe_util:rec(?wxNotifyEvent_IsAllowed). -spec veto(This) -> 'ok' when This::wxNotifyEvent(). veto(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxNotifyEvent), wxe_util:queue_cmd(This,?get_env(),?wxNotifyEvent_Veto). setString(This,String) -> wxCommandEvent:setString(This,String). setInt(This,IntCommand) -> wxCommandEvent:setInt(This,IntCommand). isSelection(This) -> wxCommandEvent:isSelection(This). isChecked(This) -> wxCommandEvent:isChecked(This). getString(This) -> wxCommandEvent:getString(This). getSelection(This) -> wxCommandEvent:getSelection(This). getInt(This) -> wxCommandEvent:getInt(This). getExtraLong(This) -> wxCommandEvent:getExtraLong(This). getClientData(This) -> wxCommandEvent:getClientData(This). stopPropagation(This) -> wxEvent:stopPropagation(This). skip(This, Options) -> wxEvent:skip(This, Options). skip(This) -> wxEvent:skip(This). shouldPropagate(This) -> wxEvent:shouldPropagate(This). resumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel). isCommandEvent(This) -> wxEvent:isCommandEvent(This). getTimestamp(This) -> wxEvent:getTimestamp(This). getSkipped(This) -> wxEvent:getSkipped(This). getId(This) -> wxEvent:getId(This).
c8a7e49f1663411c0350cee868c8fdcef13b2c1f1bf84f1d9ed5ab294718a449
haskell/cabal
cabal.test.hs
import Test.Cabal.Prelude main = cabalTest $ do void . fails $ cabal' "v2-run" ["script.hs"]
null
https://raw.githubusercontent.com/haskell/cabal/bbc11f1c71651e910976c16498bc4871d7b416ea/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptBad/cabal.test.hs
haskell
import Test.Cabal.Prelude main = cabalTest $ do void . fails $ cabal' "v2-run" ["script.hs"]
f63e1e09b95b2c6bb2b2ab736c406e558d0a46194137c269133a524ef39aca02
cj1128/sicp-review
2.50.scm
(define (flip-horiz painter) (transform-painter painter (make-vect 1.0 0.0) (make-vect 0.0 0.0) (make-vect 1.0 1.0))) (define (rotate180 painter) (transform-painter painter (make-vect 1.0 1.0) (make-vect 0.0 1.0) (make-vect 1.0 0.0))) (define (rotate270 painter) (transform-painter painter (make-vect 0.0 1.0) (make-vect 0.0 0.0) (make-vect 1.0 1.0)))
null
https://raw.githubusercontent.com/cj1128/sicp-review/efaa2f863b7f03c51641c22d701bac97e398a050/chapter-2/2.2/2.50.scm
scheme
(define (flip-horiz painter) (transform-painter painter (make-vect 1.0 0.0) (make-vect 0.0 0.0) (make-vect 1.0 1.0))) (define (rotate180 painter) (transform-painter painter (make-vect 1.0 1.0) (make-vect 0.0 1.0) (make-vect 1.0 0.0))) (define (rotate270 painter) (transform-painter painter (make-vect 0.0 1.0) (make-vect 0.0 0.0) (make-vect 1.0 1.0)))
caa9140c3e46b92ab1d3dbe81490be060e593172d082db7bc31404e7241939f4
rtoy/cmucl
boot-19f.lisp
;;;; Boot file for changing the fasl file version numbers to 19e . ;;;; (in-package :c) (setf lisp::*enable-package-locked-errors* nil) ;;; Note that BYTE - FASL - FILE - VERSION is a constant . ;;; ( Be sure to change BYTE - FASL - FILE - VERSION in ;;; compiler/byte-comp.lisp to the correct value too!) ;;; (setf (symbol-value 'byte-fasl-file-version) #x19f) (setf (backend-fasl-file-version *target-backend*) #x19f) ;;; ;;; Don't check fasl versions in the compiling Lisp because we'll ;;; load files compiled with the new version numbers. ;;; (setq lisp::*skip-fasl-file-version-check* t) ;;; ;;; This is here because BYTE-FASL-FILE-VERSION is constant-folded in ;;; OPEN-FASL-FILE. To make the new version number take effect, we ;;; have to redefine the function. ;;; (defun open-fasl-file (name where &optional byte-p) (declare (type pathname name)) (let* ((stream (open name :direction :output :if-exists :new-version :element-type '(unsigned-byte 8))) (res (make-fasl-file :stream stream))) (multiple-value-bind (version f-vers f-imp) (if byte-p (values "Byte code" byte-fasl-file-version (backend-byte-fasl-file-implementation *backend*)) (values (backend-version *backend*) (backend-fasl-file-version *backend*) (backend-fasl-file-implementation *backend*))) (format stream "FASL FILE output from ~A.~@ Compiled ~A on ~A~@ Compiler ~A, Lisp ~A~@ Targeted for ~A, FASL version ~X~%" where (ext:format-universal-time nil (get-universal-time)) (machine-instance) compiler-version (lisp-implementation-version) version f-vers) ;; ;; Terminate header. (dump-byte 255 res) ;; ;; Specify code format. (dump-fop 'lisp::fop-long-code-format res) (dump-byte f-imp res) (dump-unsigned-32 f-vers res)) res))
null
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/bootfiles/19e/boot-19f.lisp
lisp
compiler/byte-comp.lisp to the correct value too!) Don't check fasl versions in the compiling Lisp because we'll load files compiled with the new version numbers. This is here because BYTE-FASL-FILE-VERSION is constant-folded in OPEN-FASL-FILE. To make the new version number take effect, we have to redefine the function. Terminate header. Specify code format.
Boot file for changing the fasl file version numbers to 19e . (in-package :c) (setf lisp::*enable-package-locked-errors* nil) Note that BYTE - FASL - FILE - VERSION is a constant . ( Be sure to change BYTE - FASL - FILE - VERSION in (setf (symbol-value 'byte-fasl-file-version) #x19f) (setf (backend-fasl-file-version *target-backend*) #x19f) (setq lisp::*skip-fasl-file-version-check* t) (defun open-fasl-file (name where &optional byte-p) (declare (type pathname name)) (let* ((stream (open name :direction :output :if-exists :new-version :element-type '(unsigned-byte 8))) (res (make-fasl-file :stream stream))) (multiple-value-bind (version f-vers f-imp) (if byte-p (values "Byte code" byte-fasl-file-version (backend-byte-fasl-file-implementation *backend*)) (values (backend-version *backend*) (backend-fasl-file-version *backend*) (backend-fasl-file-implementation *backend*))) (format stream "FASL FILE output from ~A.~@ Compiled ~A on ~A~@ Compiler ~A, Lisp ~A~@ Targeted for ~A, FASL version ~X~%" where (ext:format-universal-time nil (get-universal-time)) (machine-instance) compiler-version (lisp-implementation-version) version f-vers) (dump-byte 255 res) (dump-fop 'lisp::fop-long-code-format res) (dump-byte f-imp res) (dump-unsigned-32 f-vers res)) res))
f9bdba2d1967bd7b85c448169cd1ac799c65168d2d0e7e70ca57c01a37a94ec0
expipiplus1/vulkan
Bracket.hs
module VK.Bracket ( brackets ) where import Data.List ( (\\) ) import qualified Data.Map as Map import qualified Data.Text.Extra as T import Data.Vector ( Vector ) import Polysemy import Relude hiding ( Handle , Type ) import Bracket import CType import Error import Marshal.Command import Marshal.Scheme import Render.Element import Render.Names import Render.SpecInfo import Render.Utils import Spec.Parse brackets :: forall r . (HasErr r, HasRenderParams r, HasSpecInfo r, HasRenderedNames r) => Vector MarshaledCommand -> Vector Handle -> Sem r (Vector (CName, CName, RenderElement)) ^ ( Creating command , Bracket command , RenderElem ) brackets marshaledCommands handles = context "brackets" $ do let getMarshaledCommand = let mcMap = Map.fromList [ (mcName, m) | m@MarshaledCommand {..} <- toList marshaledCommands ] in \n -> note ("Unable to find marshaled command " <> show n) . (`Map.lookup` mcMap) $ n autoBracket' bracketType create destroy with = do create' <- getMarshaledCommand create destroy' <- getMarshaledCommand destroy autoBracket bracketType create' destroy' with cdBracket h = autoBracket' BracketCPS (CName ("vkCreate" <> h)) (CName ("vkDestroy" <> h)) (CName ("vkWith" <> h)) afBracket h = autoBracket' BracketCPS (CName ("vkAllocate" <> h)) (CName ("vkFree" <> h)) (CName ("vkWith" <> h)) cmdBeBracket h = autoBracket' BracketBookend (CName ("vkCmdBegin" <> h)) (CName ("vkCmdEnd" <> h)) (CName ("vkCmdUse" <> h)) -- TODO: Missing functions here should be warnings, because we might be -- generating a different version of the spec. bs <- sequenceV [ cdBracket "Instance" , cdBracket "Device" , cdBracket "CommandPool" , cdBracket "Buffer" , cdBracket "BufferView" , cdBracket "Image" , cdBracket "ImageView" , cdBracket "ShaderModule" , cdBracket "PipelineLayout" , cdBracket "Sampler" , cdBracket "DescriptorSetLayout" , cdBracket "DescriptorPool" , cdBracket "Fence" , cdBracket "Semaphore" , cdBracket "Event" , cdBracket "QueryPool" , cdBracket "Framebuffer" , cdBracket "RenderPass" , cdBracket "PipelineCache" , cdBracket "IndirectCommandsLayoutNV" , cdBracket "DescriptorUpdateTemplate" , cdBracket "SamplerYcbcrConversion" , cdBracket "ValidationCacheEXT" , cdBracket "AccelerationStructureKHR" , cdBracket "AccelerationStructureNV" ^ TODO : remove when generating from a pre 1.2.162 spec , cdBracket "SwapchainKHR" , cdBracket "DebugReportCallbackEXT" , cdBracket "DebugUtilsMessengerEXT" , cdBracket "DeferredOperationKHR" , cdBracket "PrivateDataSlot" -- , cdBracket "VideoSessionKHR" , cdBracket " VideoSessionParametersKHR " , cdBracket "CuModuleNVX" , cdBracket "CuFunctionNVX" , cdBracket "BufferCollectionFUCHSIA" , cdBracket "OpticalFlowSessionNV" , cdBracket "MicromapEXT" , pure withCommmandBuffers , afBracket "Memory" , pure withDescriptorSets , autoBracket' BracketCPS "vkCreateGraphicsPipelines" "vkDestroyPipeline" "vkWithGraphicsPipelines" , autoBracket' BracketCPS "vkCreateComputePipelines" "vkDestroyPipeline" "vkWithComputePipelines" , autoBracket' BracketCPS "vkCreateRayTracingPipelinesKHR" "vkDestroyPipeline" "vkWithRayTracingPipelinesKHR" , autoBracket' BracketCPS "vkCreateRayTracingPipelinesNV" "vkDestroyPipeline" "vkWithRayTracingPipelinesNV" , autoBracket' BracketCPS "vkMapMemory" "vkUnmapMemory" "vkWithMappedMemory" , autoBracket' BracketBookend "vkBeginCommandBuffer" "vkEndCommandBuffer" "vkUseCommandBuffer" , cmdBeBracket "Query" , cmdBeBracket "ConditionalRenderingEXT" , cmdBeBracket "RenderPass" , cmdBeBracket "DebugUtilsLabelEXT" , cmdBeBracket "RenderPass2" , cmdBeBracket "TransformFeedbackEXT" , cmdBeBracket "QueryIndexedEXT" , cmdBeBracket "Rendering" ] -- -- Check that we can generate all the handles -- let ignoredHandles = [ "VkPhysicalDevice" , "VkQueue" , "VkDisplayKHR" , "VkDisplayModeKHR" , "VkSurfaceKHR" , "VkPerformanceConfigurationINTEL" ] handleNames = hName <$> handles -- A crude way of getting all the type names we generate createdBracketNames = [ n | Bracket {..} <- bs , TypeName n <- [ t | Normal t <- bInnerTypes ] <> [ t | Vector _ (Normal t) <- bInnerTypes ] ] unhandledHandles = toList handleNames \\ (createdBracketNames ++ ignoredHandles) unless (null unhandledHandles) $ throw ("Unbracketed handles: " <> show unhandledHandles) fromList <$> traverseV (renderBracket paramName) bs withCommmandBuffers :: Bracket withCommmandBuffers = Bracket { bInnerTypes = [Vector NotNullable (Normal (TypeName "VkCommandBuffer"))] , bWrapperName = "vkWithCommandBuffers" , bCreate = "vkAllocateCommandBuffers" , bDestroy = "vkFreeCommandBuffers" , bCreateArguments = [ Provided "device" (Normal (TypeName "VkDevice")) , Provided "pAllocateInfo" (Normal (TypeName "VkCommandBufferAllocateInfo")) ] , bDestroyArguments = [ Provided "device" (Normal (TypeName "VkDevice")) , Member "pAllocateInfo" "commandPool" , Resource IdentityResource 0 ] , bDestroyIndividually = DoNotDestroyIndividually , bBracketType = BracketCPS , bDestroyReturnTypes = [] } withDescriptorSets :: Bracket withDescriptorSets = Bracket { bInnerTypes = [Vector NotNullable (Normal (TypeName "VkDescriptorSet"))] , bWrapperName = "vkWithDescriptorSets" , bCreate = "vkAllocateDescriptorSets" , bDestroy = "vkFreeDescriptorSets" , bCreateArguments = [ Provided "device" (Normal (TypeName "VkDevice")) , Provided "pAllocateInfo" (Normal (TypeName "VkDescriptorSetAllocateInfo")) ] , bDestroyArguments = [ Provided "device" (Normal (TypeName "VkDevice")) , Member "pAllocateInfo" "descriptorPool" , Resource IdentityResource 0 ] , bDestroyIndividually = DoNotDestroyIndividually , bBracketType = BracketCPS , bDestroyReturnTypes = [] } dropVk :: Text -> Text dropVk t = if "vk" `T.isPrefixOf` T.toLower t then T.dropWhile (== '_') . T.drop 2 $ t else t paramName :: Text -> Text paramName = unReservedWord . T.lowerCaseFirst . dropVk
null
https://raw.githubusercontent.com/expipiplus1/vulkan/a46784a1079839381e18cfe37a8c0d6ce29a0c90/generate-new/vk/VK/Bracket.hs
haskell
TODO: Missing functions here should be warnings, because we might be generating a different version of the spec. , cdBracket "VideoSessionKHR" Check that we can generate all the handles A crude way of getting all the type names we generate
module VK.Bracket ( brackets ) where import Data.List ( (\\) ) import qualified Data.Map as Map import qualified Data.Text.Extra as T import Data.Vector ( Vector ) import Polysemy import Relude hiding ( Handle , Type ) import Bracket import CType import Error import Marshal.Command import Marshal.Scheme import Render.Element import Render.Names import Render.SpecInfo import Render.Utils import Spec.Parse brackets :: forall r . (HasErr r, HasRenderParams r, HasSpecInfo r, HasRenderedNames r) => Vector MarshaledCommand -> Vector Handle -> Sem r (Vector (CName, CName, RenderElement)) ^ ( Creating command , Bracket command , RenderElem ) brackets marshaledCommands handles = context "brackets" $ do let getMarshaledCommand = let mcMap = Map.fromList [ (mcName, m) | m@MarshaledCommand {..} <- toList marshaledCommands ] in \n -> note ("Unable to find marshaled command " <> show n) . (`Map.lookup` mcMap) $ n autoBracket' bracketType create destroy with = do create' <- getMarshaledCommand create destroy' <- getMarshaledCommand destroy autoBracket bracketType create' destroy' with cdBracket h = autoBracket' BracketCPS (CName ("vkCreate" <> h)) (CName ("vkDestroy" <> h)) (CName ("vkWith" <> h)) afBracket h = autoBracket' BracketCPS (CName ("vkAllocate" <> h)) (CName ("vkFree" <> h)) (CName ("vkWith" <> h)) cmdBeBracket h = autoBracket' BracketBookend (CName ("vkCmdBegin" <> h)) (CName ("vkCmdEnd" <> h)) (CName ("vkCmdUse" <> h)) bs <- sequenceV [ cdBracket "Instance" , cdBracket "Device" , cdBracket "CommandPool" , cdBracket "Buffer" , cdBracket "BufferView" , cdBracket "Image" , cdBracket "ImageView" , cdBracket "ShaderModule" , cdBracket "PipelineLayout" , cdBracket "Sampler" , cdBracket "DescriptorSetLayout" , cdBracket "DescriptorPool" , cdBracket "Fence" , cdBracket "Semaphore" , cdBracket "Event" , cdBracket "QueryPool" , cdBracket "Framebuffer" , cdBracket "RenderPass" , cdBracket "PipelineCache" , cdBracket "IndirectCommandsLayoutNV" , cdBracket "DescriptorUpdateTemplate" , cdBracket "SamplerYcbcrConversion" , cdBracket "ValidationCacheEXT" , cdBracket "AccelerationStructureKHR" , cdBracket "AccelerationStructureNV" ^ TODO : remove when generating from a pre 1.2.162 spec , cdBracket "SwapchainKHR" , cdBracket "DebugReportCallbackEXT" , cdBracket "DebugUtilsMessengerEXT" , cdBracket "DeferredOperationKHR" , cdBracket "PrivateDataSlot" , cdBracket " VideoSessionParametersKHR " , cdBracket "CuModuleNVX" , cdBracket "CuFunctionNVX" , cdBracket "BufferCollectionFUCHSIA" , cdBracket "OpticalFlowSessionNV" , cdBracket "MicromapEXT" , pure withCommmandBuffers , afBracket "Memory" , pure withDescriptorSets , autoBracket' BracketCPS "vkCreateGraphicsPipelines" "vkDestroyPipeline" "vkWithGraphicsPipelines" , autoBracket' BracketCPS "vkCreateComputePipelines" "vkDestroyPipeline" "vkWithComputePipelines" , autoBracket' BracketCPS "vkCreateRayTracingPipelinesKHR" "vkDestroyPipeline" "vkWithRayTracingPipelinesKHR" , autoBracket' BracketCPS "vkCreateRayTracingPipelinesNV" "vkDestroyPipeline" "vkWithRayTracingPipelinesNV" , autoBracket' BracketCPS "vkMapMemory" "vkUnmapMemory" "vkWithMappedMemory" , autoBracket' BracketBookend "vkBeginCommandBuffer" "vkEndCommandBuffer" "vkUseCommandBuffer" , cmdBeBracket "Query" , cmdBeBracket "ConditionalRenderingEXT" , cmdBeBracket "RenderPass" , cmdBeBracket "DebugUtilsLabelEXT" , cmdBeBracket "RenderPass2" , cmdBeBracket "TransformFeedbackEXT" , cmdBeBracket "QueryIndexedEXT" , cmdBeBracket "Rendering" ] let ignoredHandles = [ "VkPhysicalDevice" , "VkQueue" , "VkDisplayKHR" , "VkDisplayModeKHR" , "VkSurfaceKHR" , "VkPerformanceConfigurationINTEL" ] handleNames = hName <$> handles createdBracketNames = [ n | Bracket {..} <- bs , TypeName n <- [ t | Normal t <- bInnerTypes ] <> [ t | Vector _ (Normal t) <- bInnerTypes ] ] unhandledHandles = toList handleNames \\ (createdBracketNames ++ ignoredHandles) unless (null unhandledHandles) $ throw ("Unbracketed handles: " <> show unhandledHandles) fromList <$> traverseV (renderBracket paramName) bs withCommmandBuffers :: Bracket withCommmandBuffers = Bracket { bInnerTypes = [Vector NotNullable (Normal (TypeName "VkCommandBuffer"))] , bWrapperName = "vkWithCommandBuffers" , bCreate = "vkAllocateCommandBuffers" , bDestroy = "vkFreeCommandBuffers" , bCreateArguments = [ Provided "device" (Normal (TypeName "VkDevice")) , Provided "pAllocateInfo" (Normal (TypeName "VkCommandBufferAllocateInfo")) ] , bDestroyArguments = [ Provided "device" (Normal (TypeName "VkDevice")) , Member "pAllocateInfo" "commandPool" , Resource IdentityResource 0 ] , bDestroyIndividually = DoNotDestroyIndividually , bBracketType = BracketCPS , bDestroyReturnTypes = [] } withDescriptorSets :: Bracket withDescriptorSets = Bracket { bInnerTypes = [Vector NotNullable (Normal (TypeName "VkDescriptorSet"))] , bWrapperName = "vkWithDescriptorSets" , bCreate = "vkAllocateDescriptorSets" , bDestroy = "vkFreeDescriptorSets" , bCreateArguments = [ Provided "device" (Normal (TypeName "VkDevice")) , Provided "pAllocateInfo" (Normal (TypeName "VkDescriptorSetAllocateInfo")) ] , bDestroyArguments = [ Provided "device" (Normal (TypeName "VkDevice")) , Member "pAllocateInfo" "descriptorPool" , Resource IdentityResource 0 ] , bDestroyIndividually = DoNotDestroyIndividually , bBracketType = BracketCPS , bDestroyReturnTypes = [] } dropVk :: Text -> Text dropVk t = if "vk" `T.isPrefixOf` T.toLower t then T.dropWhile (== '_') . T.drop 2 $ t else t paramName :: Text -> Text paramName = unReservedWord . T.lowerCaseFirst . dropVk
60dfb1b3710d5b5182123f8dec7901e1baee379469fd06302716dccc1c830bb6
gator1/jepsen
model.clj
(ns jepsen.model "Functional abstract models of database behavior." (:refer-clojure :exclude [set]) (:import knossos.model.Model (clojure.lang PersistentQueue)) (:use clojure.tools.logging) (:require [clojure.core :as core] [knossos.model :as knossos] [multiset.core :as multiset])) (def inconsistent knossos/inconsistent) (defrecord NoOp [] Model (step [m op] m)) (def noop "A model which always returns itself, unchanged." (NoOp.)) (defrecord CASRegister [value] Model (step [r op] (condp = (:f op) :write (CASRegister. (:value op)) :cas (let [[cur new] (:value op)] (if (= cur value) (CASRegister. new) (inconsistent (str "can't CAS " value " from " cur " to " new)))) :read (if (or (nil? (:value op)) (= value (:value op))) r (inconsistent (str "can't read " (:value op) " from register " value)))))) (defn cas-register "A compare-and-set register" ([] (cas-register nil)) ([value] (CASRegister. value))) (defrecord Mutex [locked?] Model (step [r op] (condp = (:f op) :acquire (if locked? (inconsistent "already held") (Mutex. true)) :release (if locked? (Mutex. false) (inconsistent "not held"))))) (defn mutex "A single mutex responding to :acquire and :release messages" [] (Mutex. false)) (defrecord Set [s] Model (step [this op] (condp = (:f op) :add (Set. (conj s (:value op))) :read (if (= s (:value op)) this (inconsistent (str "can't read " (pr-str (:value op)) " from " (pr-str s))))))) (defn set "A set which responds to :add and :read." [] (Set. #{})) (defrecord UnorderedQueue [pending] Model (step [r op] (condp = (:f op) :enqueue (UnorderedQueue. (conj pending (:value op))) :dequeue (if (contains? pending (:value op)) (UnorderedQueue. (disj pending (:value op))) (inconsistent (str "can't dequeue " (:value op))))))) (defn unordered-queue "A queue which does not order its pending elements." [] (UnorderedQueue. (multiset/multiset))) (defrecord FIFOQueue [pending] Model (step [r op] (condp = (:f op) :enqueue (FIFOQueue. (conj pending (:value op))) :dequeue (cond (zero? (count pending)) (inconsistent (str "can't dequeue " (:value op) " from empty queue")) (= (:value op) (peek pending)) (FIFOQueue. (pop pending)) :else (inconsistent (str "can't dequeue " (:value op))))))) (defn fifo-queue "A FIFO queue." [] (FIFOQueue. PersistentQueue/EMPTY))
null
https://raw.githubusercontent.com/gator1/jepsen/1932cbd72cbc1f6c2a27abe0fe347ea989f0cfbb/jepsen/src/jepsen/model.clj
clojure
(ns jepsen.model "Functional abstract models of database behavior." (:refer-clojure :exclude [set]) (:import knossos.model.Model (clojure.lang PersistentQueue)) (:use clojure.tools.logging) (:require [clojure.core :as core] [knossos.model :as knossos] [multiset.core :as multiset])) (def inconsistent knossos/inconsistent) (defrecord NoOp [] Model (step [m op] m)) (def noop "A model which always returns itself, unchanged." (NoOp.)) (defrecord CASRegister [value] Model (step [r op] (condp = (:f op) :write (CASRegister. (:value op)) :cas (let [[cur new] (:value op)] (if (= cur value) (CASRegister. new) (inconsistent (str "can't CAS " value " from " cur " to " new)))) :read (if (or (nil? (:value op)) (= value (:value op))) r (inconsistent (str "can't read " (:value op) " from register " value)))))) (defn cas-register "A compare-and-set register" ([] (cas-register nil)) ([value] (CASRegister. value))) (defrecord Mutex [locked?] Model (step [r op] (condp = (:f op) :acquire (if locked? (inconsistent "already held") (Mutex. true)) :release (if locked? (Mutex. false) (inconsistent "not held"))))) (defn mutex "A single mutex responding to :acquire and :release messages" [] (Mutex. false)) (defrecord Set [s] Model (step [this op] (condp = (:f op) :add (Set. (conj s (:value op))) :read (if (= s (:value op)) this (inconsistent (str "can't read " (pr-str (:value op)) " from " (pr-str s))))))) (defn set "A set which responds to :add and :read." [] (Set. #{})) (defrecord UnorderedQueue [pending] Model (step [r op] (condp = (:f op) :enqueue (UnorderedQueue. (conj pending (:value op))) :dequeue (if (contains? pending (:value op)) (UnorderedQueue. (disj pending (:value op))) (inconsistent (str "can't dequeue " (:value op))))))) (defn unordered-queue "A queue which does not order its pending elements." [] (UnorderedQueue. (multiset/multiset))) (defrecord FIFOQueue [pending] Model (step [r op] (condp = (:f op) :enqueue (FIFOQueue. (conj pending (:value op))) :dequeue (cond (zero? (count pending)) (inconsistent (str "can't dequeue " (:value op) " from empty queue")) (= (:value op) (peek pending)) (FIFOQueue. (pop pending)) :else (inconsistent (str "can't dequeue " (:value op))))))) (defn fifo-queue "A FIFO queue." [] (FIFOQueue. PersistentQueue/EMPTY))
1a8471b28c5cc3d0540681ce0cff058e906f92ff252688fc93f16ca02986bc7a
fujita-y/ypsilon
srfi-64.scm
#!nobacktrace (define-library (srfi srfi-64) (import (srfi 64)) (export test-begin test-end test-group test-group-with-cleanup test-skip test-expect-fail test-match-name test-match-nth test-match-all test-match-any test-assert test-eqv test-eq test-equal test-approximate test-error test-read-eval-string test-apply test-with-runner test-exit test-runner-null test-runner? test-runner-reset test-result-alist test-result-alist! test-result-ref test-result-set! test-result-remove test-result-clear test-runner-pass-count test-runner-fail-count test-runner-xpass-count test-runner-xfail-count test-runner-skip-count test-runner-test-name test-runner-group-path test-runner-group-stack test-runner-aux-value test-runner-aux-value! test-result-kind test-passed? test-runner-on-test-begin test-runner-on-test-begin! test-runner-on-test-end test-runner-on-test-end! test-runner-on-group-begin test-runner-on-group-begin! test-runner-on-group-end test-runner-on-group-end! test-runner-on-final test-runner-on-final! test-runner-on-bad-count test-runner-on-bad-count! test-runner-on-bad-end-name test-runner-on-bad-end-name! test-runner-factory test-runner-create test-runner-current test-runner-get test-runner-simple test-on-group-begin-simple test-on-group-end-simple test-on-final-simple test-on-test-begin-simple test-on-test-end-simple test-on-bad-count-simple test-on-bad-end-name-simple))
null
https://raw.githubusercontent.com/fujita-y/ypsilon/44260d99e24000f9847e79c94826c3d9b76872c2/sitelib/srfi/srfi-64.scm
scheme
#!nobacktrace (define-library (srfi srfi-64) (import (srfi 64)) (export test-begin test-end test-group test-group-with-cleanup test-skip test-expect-fail test-match-name test-match-nth test-match-all test-match-any test-assert test-eqv test-eq test-equal test-approximate test-error test-read-eval-string test-apply test-with-runner test-exit test-runner-null test-runner? test-runner-reset test-result-alist test-result-alist! test-result-ref test-result-set! test-result-remove test-result-clear test-runner-pass-count test-runner-fail-count test-runner-xpass-count test-runner-xfail-count test-runner-skip-count test-runner-test-name test-runner-group-path test-runner-group-stack test-runner-aux-value test-runner-aux-value! test-result-kind test-passed? test-runner-on-test-begin test-runner-on-test-begin! test-runner-on-test-end test-runner-on-test-end! test-runner-on-group-begin test-runner-on-group-begin! test-runner-on-group-end test-runner-on-group-end! test-runner-on-final test-runner-on-final! test-runner-on-bad-count test-runner-on-bad-count! test-runner-on-bad-end-name test-runner-on-bad-end-name! test-runner-factory test-runner-create test-runner-current test-runner-get test-runner-simple test-on-group-begin-simple test-on-group-end-simple test-on-final-simple test-on-test-begin-simple test-on-test-end-simple test-on-bad-count-simple test-on-bad-end-name-simple))
389240be0f8d97129b8d93364ca66de3103b0ee90cba2c7ab16714e139d37a3a
ocaml-opam/opam-rt
utils.mli
* Copyright ( c ) 2013 - 2020 OCamlPro * Authors < > , * < > , * < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2013-2020 OCamlPro * Authors Thomas Gazagnaire <>, * Louis Gesbert <>, * Raja Boujbel <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open OpamTypes exception Not_available exception Allowed_failure val log: ('a, Format.formatter, unit) format -> 'a val set_seed: int -> unit val set_datadir: dirname -> unit val data: string -> filename (** Config *) type config = { repo_name : OpamRepositoryName.t; repo_root : dirname; repo_url : url; opam_root : dirname; contents_root: dirname; } val create_config: OpamUrl.backend option -> dirname -> config val read_config: dirname -> config val write_repo_config: dirname -> repository_name -> OpamUrl.t * trust_anchors option -> unit (** Init *) val shuffle: 'a list -> 'a list val package: string -> int -> OpamUrl.backend option -> dirname -> ?gener_archive:bool -> int -> Packages.t (* Repository initialisation *) val create_repo_with_history: dirname -> dirname -> unit val create_simple_repo: dirname -> dirname -> OpamUrl.backend option -> unit (** opam *) type installed = { installed: package_set; installed_roots: package_set } val read_installed: dirname -> installed val check_installed: dirname -> ?roots:package list -> package list -> unit val check_pinned: dirname -> ?kind:string -> package list -> unit (* Repo server *) val update_server_index: dirname -> OpamUrl.t -> unit val start_file_server: dirname -> OpamUrl.t -> unit -> unit (** Run *) val run: ('a -> unit) -> 'a -> unit val check_and_run: OpamUrl.backend option -> ('a -> unit) -> 'a -> unit val step: unit -> string -> unit val should_fail: int -> OpamStd.Sys.exit_reason -> unit val todo: unit -> 'a
null
https://raw.githubusercontent.com/ocaml-opam/opam-rt/2f42d8dcdbd9f16e0e385314a8bf9396cb8a88fa/src/tests/utils.mli
ocaml
* Config * Init Repository initialisation * opam Repo server * Run
* Copyright ( c ) 2013 - 2020 OCamlPro * Authors < > , * < > , * < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2013-2020 OCamlPro * Authors Thomas Gazagnaire <>, * Louis Gesbert <>, * Raja Boujbel <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open OpamTypes exception Not_available exception Allowed_failure val log: ('a, Format.formatter, unit) format -> 'a val set_seed: int -> unit val set_datadir: dirname -> unit val data: string -> filename type config = { repo_name : OpamRepositoryName.t; repo_root : dirname; repo_url : url; opam_root : dirname; contents_root: dirname; } val create_config: OpamUrl.backend option -> dirname -> config val read_config: dirname -> config val write_repo_config: dirname -> repository_name -> OpamUrl.t * trust_anchors option -> unit val shuffle: 'a list -> 'a list val package: string -> int -> OpamUrl.backend option -> dirname -> ?gener_archive:bool -> int -> Packages.t val create_repo_with_history: dirname -> dirname -> unit val create_simple_repo: dirname -> dirname -> OpamUrl.backend option -> unit type installed = { installed: package_set; installed_roots: package_set } val read_installed: dirname -> installed val check_installed: dirname -> ?roots:package list -> package list -> unit val check_pinned: dirname -> ?kind:string -> package list -> unit val update_server_index: dirname -> OpamUrl.t -> unit val start_file_server: dirname -> OpamUrl.t -> unit -> unit val run: ('a -> unit) -> 'a -> unit val check_and_run: OpamUrl.backend option -> ('a -> unit) -> 'a -> unit val step: unit -> string -> unit val should_fail: int -> OpamStd.Sys.exit_reason -> unit val todo: unit -> 'a
6b7e5572ad71ec8706cacf879ed9098bc67d0c0c8cfbf580c80a82032dcb685d
cgoldammer/chess-database-backend
StatsHelpers.hs
|Assorted statistical functions needed as part of the app . module Services.StatsHelpers where -- Arithmetic mean mean :: (Floating a) => [a] -> a mean xs = sum xs / (fromIntegral . length) xs var :: (Floating a) => [a] -> a var xs = sum (map (\x -> (x - m)^(2::Integer)) xs) / (fromIntegral (length xs)-1) where m = mean xs stdDev :: (Floating a) => [a] -> a stdDev x = sqrt $ var x stdError :: (Floating a) => [a] -> a stdError x = stdDev x / sqrt num where num = fromIntegral $ length x intAverage :: [Int] -> Int intAverage x = div (sum x) (length x)
null
https://raw.githubusercontent.com/cgoldammer/chess-database-backend/03b6b8d3072941e7da395eb4371ece588093e140/src/Services/StatsHelpers.hs
haskell
Arithmetic mean
|Assorted statistical functions needed as part of the app . module Services.StatsHelpers where mean :: (Floating a) => [a] -> a mean xs = sum xs / (fromIntegral . length) xs var :: (Floating a) => [a] -> a var xs = sum (map (\x -> (x - m)^(2::Integer)) xs) / (fromIntegral (length xs)-1) where m = mean xs stdDev :: (Floating a) => [a] -> a stdDev x = sqrt $ var x stdError :: (Floating a) => [a] -> a stdError x = stdDev x / sqrt num where num = fromIntegral $ length x intAverage :: [Int] -> Int intAverage x = div (sum x) (length x)
d7b280a6e76f13891c680856a643b69295424af20312e6e94cf851f9f519adf3
skanev/playground
90.scm
SICP exercise 2.90 ; ; Suppose we want to have a polynomial system that is efficient for both sparse and dense polynomials . One way to do this is to allow both kinds of ; term-list representations in our system. The situation is analogous to the complex - number example of section 2.4 , where we allowed both rectangular and ; polar representations. To do this we must distinguish different types of ; term lists and make the operations on term lists generic. Redesign the ; polynomial system to implement this generalization. This is a major effort, ; not a local change. ; Come now, it is not a major effort. It is not uber simple either, but hey, ; it is not supposed to be either. We base this on the prevoius exercise: (define (attach-tag type-tag contents) (cons type-tag contents)) (define (type-tag datum) (if (pair? datum) (car datum) (error "Bad tagged datum - TYPE-TAG" datum))) (define (contents datum) (if (pair? datum) (cdr datum) (error "Bad tagged datum - CONTENTS" datum))) (define table (make-hash)) (define (put op type item) (hash-set! table (list op type) item)) (define (get op type) (hash-ref table (list op type) #f)) (define (put-coercion from to op) (put 'coerce (list from to) op)) (define (get-coercion from to) (get 'coerce (list from to))) ; The type tower, supetype, supertype?, raise and project: (put 'supertype 'integer 'rational) (put 'supertype 'rational 'scheme-number) (put 'supertype 'scheme-number 'real) (define (supertype type) (get 'supertype type)) (define (supertype? a b) (let ((super (supertype a))) (cond ((equal? super b) #t) ((not super) #f) (else (supertype? super b))))) (define (same-type? a b) (equal? (type-tag a) (type-tag b))) (define (raise a) (apply-generic 'raise a)) (define (project a) (apply-generic 'project a)) (define (projectable? a) (get 'project (list (type-tag a)))) (define (raisable? a) (get 'raise (list (type-tag a)))) ; Now a simplification procedure. It will be called simplify instead of drop, ; because drop is already reserved: (define (simplify x) (cond ((not (projectable? x)) x) ((equ? (raise (project x)) x) (simplify (project x))) (else x))) ; Now the generic arithmemtic procedures. (define (add x y) (apply-generic 'add x y)) (define (sub x y) (apply-generic 'sub x y)) (define (mul x y) (apply-generic 'mul x y)) (define (div x y) (apply-generic 'div x y)) (define (neg x) (apply-generic 'neg x)) (define (equ? x y) (apply-generic 'equ? x y)) (define (square-root x) (apply-generic 'square-root x)) (define (sine x) (apply-generic 'sine x)) (define (cosine x) (apply-generic 'cosine x)) (define (arctangent x y) (apply-generic 'arctangent x y)) (define (=zero? x) (apply-generic '=zero? x)) (define (square x) (mul x x)) ; The simplification table: (define (simplifiable? op) (get 'simplifiable op)) (put 'simplifiable 'add #t) (put 'simplifiable 'sub #t) (put 'simplifiable 'mul #t) (put 'simplifiable 'div #t) (put 'simplifiable 'neg #t) (put 'simplifiable 'square-root #t) (put 'simplifiable 'sine #t) (put 'simplifiable 'cosine #t) (put 'simplifiable 'arctangent #t) (put 'simplifiable 'real-part #t) (put 'simplifiable 'imag-part #t) (put 'simplifiable 'magnitude #t) (put 'simplifiable 'angle #t) ; Integers: (let () (define (tag x) (attach-tag 'integer x)) (put 'add '(integer integer) (lambda (x y) (tag (+ x y)))) (put 'sub '(integer integer) (lambda (x y) (tag (- x y)))) (put 'mul '(integer integer) (lambda (x y) (tag (* x y)))) (put 'neg '(integer) (lambda (x) (tag (- x)))) (put 'equ? '(integer integer) =) (put '=zero? '(integer) zero?) (put 'raise '(integer) (lambda (n) (make-rational n 1))) (put 'make 'integer (lambda (n) (if (exact-integer? n) (tag n) (error "Attempted to make an integer with a non-integer" n))))) (define (make-integer n) ((get 'make 'integer) n)) ; Rational numbers: (let () (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (if (and (exact-integer? n) (exact-integer? d)) (let ((g (gcd n d))) (cons (/ n g) (/ d g))) (error "Cannot construct a rational with non-exact numbers" n d))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (define (neg-rat x) (make-rat (- (numer x)) (denom x))) (define (=zero?-rat x) (zero? (numer x))) (define (raise-rat r) (make-real (exact->inexact (/ (numer r) (denom r))))) (define (project-rat r) (make-integer (truncate (/ (numer r) (denom r))))) (define (tag x) (attach-tag 'rational x)) (put 'numer '(rational) numer) (put 'denom '(rational) denom) (put 'raise '(rational) raise-rat) (put 'project '(rational) project-rat) (put '=zero? '(rational) =zero?-rat) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'neg '(rational) (lambda (x) (tag (neg-rat x)))) (put 'equ? '(rational rational) equal?) (put 'make 'rational (lambda (n d) (tag (make-rat n d))))) (define (make-rational n d) ((get 'make 'rational) n d)) (define (numer r) (apply-generic 'numer r)) (define (denom r) (apply-generic 'denom r)) ; Real numbers: (let () (define (tag x) (attach-tag 'real x)) (put 'add '(real real) (lambda (x y) (tag (+ x y)))) (put 'sub '(real real) (lambda (x y) (tag (- x y)))) (put 'mul '(real real) (lambda (x y) (tag (* x y)))) (put 'div '(real real) (lambda (x y) (tag (/ x y)))) (put 'neg '(real) (lambda (x) (tag (- x)))) (put 'sine '(real) (lambda (x) (tag (sin x)))) (put 'cosine '(real) (lambda (x) (tag (cos x)))) (put 'square-root '(real) (lambda (x) (tag (sqrt x)))) (put 'arctangent '(real real) (lambda (x y) (tag (atan x y)))) (put 'project '(real) (lambda (x) (make-rational (inexact->exact (truncate x)) 1))) (put 'equ? '(real real) =) (put '=zero? '(real) zero?) (put 'make 'real (lambda (x) (tag x)))) (define (make-real n) ((get 'make 'real) n)) And now , the polynomial package . First , the generic term - list operations . ; Note that adjoin-term uses the table, but not apply-generic. (define (make-term order coeff) (list order coeff)) (define (order term) (car term)) (define (coeff term) (cadr term)) (define (empty-termlist? term-list) (apply-generic 'empty-termlist? term-list)) (define (first-term term-list) (apply-generic 'first-term term-list)) (define (rest-terms term-list) (apply-generic 'rest-terms term-list)) (define (adjoin-term term term-list) (let ((proc (get 'adjoin-term (type-tag term-list)))) (if proc (proc term (contents term-list)) (error "No method for these types - ADJOIN-TERM" term-list)))) ; Sparse representation: (let () (define (the-empty-termlist) '()) (define (empty-termlist? term-list) (null? term-list)) (define (first-term term-list) (car term-list)) (define (rest-terms term-list) (cdr term-list)) (define (adjoin-term term term-list) (cond ((=zero? (coeff term)) term-list) ((null? term-list) (list term)) ((> (order (car term-list)) (order term)) (cons (car term-list) (adjoin-term term (cdr term-list)))) ((= (order (car term-list)) (order term)) (adjoin-term (make-term (order term) (add (coeff term) (coeff (car term-list)))) (cdr term-list))) (else (cons term term-list)))) (define (tag x) (attach-tag 'sparse x)) (put 'empty-termlist? '(sparse) empty-termlist?) (put 'first-term '(sparse) first-term) (put 'rest-terms '(sparse) (lambda (l) (tag (rest-terms l)))) (put 'adjoin-term 'sparse (lambda (term term-list) (tag (adjoin-term term term-list)))) (put 'make 'sparse (lambda () (tag (the-empty-termlist))))) (define (the-empty-sparse-termlist) ((get 'make 'sparse))) ; Dense representation: (let () (define (the-empty-termlist) '()) (define (term-list-order term-list) (- (length term-list) 1)) (define (empty-termlist? term-list) (null? term-list)) (define (first-term term-list) (make-term (term-list-order term-list) (car term-list))) (define (rest-terms term-list) (cdr term-list)) (define (adjoin-term term term-list) (let ((term-list-order (term-list-order term-list)) (term-order (order term))) (cond ((=zero? (coeff term)) term-list) ((= term-list-order term-order) (cons (add (coeff term) (car term-list)) (cdr term-list))) ((< term-order term-list-order) (cons (car term-list) (adjoin-term term (cdr term-list)))) ((> term-order term-list-order) (adjoin-term term (cons (make-integer 0) term-list)))))) (define (tag x) (attach-tag 'dense x)) (put 'first-term '(dense) first-term) (put 'rest-terms '(dense) (lambda (l) (tag (rest-terms l)))) (put 'empty-termlist? '(dense) empty-termlist?) (put 'adjoin-term 'dense (lambda (term term-list) (tag (adjoin-term term term-list)))) (put 'make 'dense (lambda () (tag (the-empty-termlist))))) (define (the-empty-dense-termlist) ((get 'make 'dense))) ; The polynomial package. Operations between polynomials with the same ; representation will preserve the type of representation. Polynomials with ; operations of mixed representation will choose an arbitrary representation ; for the result. (let () (define (make-poly variable term-list) (cons variable term-list)) (define (variable p) (car p)) (define (term-list p) (cdr p)) (define (same-variable? v1 v2) (and (variable? v1) (variable? v2) (eq? v1 v2))) (define (variable? x) (symbol? x)) (define (empty-termlist-of-type term-list) ((get 'make (type-tag term-list)))) (define (add-terms L1 L2) (cond ((empty-termlist? L1) L2) ((empty-termlist? L2) L1) (else (let ((t1 (first-term L1)) (t2 (first-term L2))) (cond ((> (order t1) (order t2)) (adjoin-term t1 (add-terms (rest-terms L1) L2))) ((< (order t1) (order t2)) (adjoin-term t2 (add-terms L1 (rest-terms L2)))) (else (adjoin-term (make-term (order t1) (add (coeff t1) (coeff t2))) (add-terms (rest-terms L1) (rest-terms L2))))))))) (define (mul-terms L1 L2) (if (empty-termlist? L1) (empty-termlist-of-type L1) (add-terms (mul-term-by-all-terms (first-term L1) L2) (mul-terms (rest-terms L1) L2)))) (define (mul-term-by-all-terms t1 L) (if (empty-termlist? L) (empty-termlist-of-type L) (let ((t2 (first-term L))) (adjoin-term (make-term (+ (order t1) (order t2)) (mul (coeff t1) (coeff t2))) (mul-term-by-all-terms t1 (rest-terms L)))))) (define (map-terms proc L) (if (empty-termlist? L) (empty-termlist-of-type L) (let ((first (first-term L)) (rest (rest-terms L))) (adjoin-term (make-term (order first) (proc (coeff first))) (map-terms proc rest))))) (define (neg-terms L) (map-terms neg L)) (define (add-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-poly (variable p1) (add-terms (term-list p1) (term-list p2))) (error "Polynomials not in same var - ADD-POLY" (list p1 p2)))) (define (mul-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-poly (variable p1) (mul-terms (term-list p1) (term-list p2))) (error "Polynomials not in same var - MUL-POLY" (list p1 p2)))) (define (sub-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (add-poly p1 (neg-poly p2)) (error "Polynomials not in same var - SUB-POLY" (list p1 p2)))) (define (neg-poly p) (make-poly (variable p) (neg-terms (term-list p)))) (define (make-const p n) (tag (make-poly (variable p) (adjoin-term (make-term 0 (make-integer n)) (empty-termlist-of-type (term-list p)))))) (define (tag p) (attach-tag 'polynomial p)) (put 'add '(polynomial polynomial) (lambda (p1 p2) (tag (add-poly p1 p2)))) (put 'sub '(polynomial polynomial) (lambda (p1 p2) (tag (sub-poly p1 p2)))) (put 'mul '(polynomial polynomial) (lambda (p1 p2) (tag (mul-poly p1 p2)))) (put '=zero? '(polynomial) (lambda (p) (empty-termlist? (term-list p)))) (put 'neg '(polynomial) (lambda (p) (tag (neg-poly p)))) (put 'add '(integer polynomial) (lambda (n p) (add (make-const p n) (tag p)))) (put 'mul '(integer polynomial) (lambda (n p) (mul (make-const p n) (tag p)))) (put 'add '(polynomial integer) (lambda (p n) (add (make-integer n) (tag p)))) (put 'mul '(polynomial integer) (lambda (p n) (mul (make-integer n) (tag p)))) (put 'make 'polynomial (lambda (var terms) (tag (make-poly var terms))))) (define (make-polynomial var terms) ((get 'make 'polynomial) var terms)) ; apply-generic with some coercion: (define (apply-generic op . args) (define (applicable? args) (get op (map type-tag args))) (define (apply-generic-failed) (error "No method for these types - APPLY-GENERIC" (list op (map type-tag args)))) (define (all-of-same-type? args) (define (check rest) (cond ((null? rest) #t) ((same-type? (car args) (car rest)) (check (cdr rest))) (else #f))) (check args)) (define (of-same-type-and-raisable? args) (and (all-of-same-type? args) (raisable? (car args)))) (define (coercable-to-same-type? args) (and (= (length args) 2) (let ((type-a (type-tag (car args))) (type-b (type-tag (cadr args)))) (or (supertype? type-a type-b) (supertype? type-b type-a))))) (define (coerce-to-same-type args) (and (= (length args) 2) (let* ((a (car args)) (b (cadr args)) (type-a (type-tag a)) (type-b (type-tag b))) (cond ((same-type? a b) (list a b)) ((supertype? type-a type-b) (coerce-to-same-type (list (raise a) b))) ((supertype? type-b type-a) (coerce-to-same-type (list a (raise b)))) (else #f))))) (define (attempt-coercion args) (let ((number-of-arguments (length args))) (cond ((of-same-type-and-raisable? args) (try (map raise args))) ((coercable-to-same-type? args) (try (coerce-to-same-type args))) (else (apply-generic-failed))))) (define (try args) (if (applicable? args) (let ((result (apply (get op (map type-tag args)) (map contents args)))) (if (simplifiable? op) (simplify result) result)) (attempt-coercion args))) (try args))
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/02/90.scm
scheme
Suppose we want to have a polynomial system that is efficient for both term-list representations in our system. The situation is analogous to the polar representations. To do this we must distinguish different types of term lists and make the operations on term lists generic. Redesign the polynomial system to implement this generalization. This is a major effort, not a local change. Come now, it is not a major effort. It is not uber simple either, but hey, it is not supposed to be either. We base this on the prevoius exercise: The type tower, supetype, supertype?, raise and project: Now a simplification procedure. It will be called simplify instead of drop, because drop is already reserved: Now the generic arithmemtic procedures. The simplification table: Integers: Rational numbers: Real numbers: Note that adjoin-term uses the table, but not apply-generic. Sparse representation: Dense representation: The polynomial package. Operations between polynomials with the same representation will preserve the type of representation. Polynomials with operations of mixed representation will choose an arbitrary representation for the result. apply-generic with some coercion:
SICP exercise 2.90 sparse and dense polynomials . One way to do this is to allow both kinds of complex - number example of section 2.4 , where we allowed both rectangular and (define (attach-tag type-tag contents) (cons type-tag contents)) (define (type-tag datum) (if (pair? datum) (car datum) (error "Bad tagged datum - TYPE-TAG" datum))) (define (contents datum) (if (pair? datum) (cdr datum) (error "Bad tagged datum - CONTENTS" datum))) (define table (make-hash)) (define (put op type item) (hash-set! table (list op type) item)) (define (get op type) (hash-ref table (list op type) #f)) (define (put-coercion from to op) (put 'coerce (list from to) op)) (define (get-coercion from to) (get 'coerce (list from to))) (put 'supertype 'integer 'rational) (put 'supertype 'rational 'scheme-number) (put 'supertype 'scheme-number 'real) (define (supertype type) (get 'supertype type)) (define (supertype? a b) (let ((super (supertype a))) (cond ((equal? super b) #t) ((not super) #f) (else (supertype? super b))))) (define (same-type? a b) (equal? (type-tag a) (type-tag b))) (define (raise a) (apply-generic 'raise a)) (define (project a) (apply-generic 'project a)) (define (projectable? a) (get 'project (list (type-tag a)))) (define (raisable? a) (get 'raise (list (type-tag a)))) (define (simplify x) (cond ((not (projectable? x)) x) ((equ? (raise (project x)) x) (simplify (project x))) (else x))) (define (add x y) (apply-generic 'add x y)) (define (sub x y) (apply-generic 'sub x y)) (define (mul x y) (apply-generic 'mul x y)) (define (div x y) (apply-generic 'div x y)) (define (neg x) (apply-generic 'neg x)) (define (equ? x y) (apply-generic 'equ? x y)) (define (square-root x) (apply-generic 'square-root x)) (define (sine x) (apply-generic 'sine x)) (define (cosine x) (apply-generic 'cosine x)) (define (arctangent x y) (apply-generic 'arctangent x y)) (define (=zero? x) (apply-generic '=zero? x)) (define (square x) (mul x x)) (define (simplifiable? op) (get 'simplifiable op)) (put 'simplifiable 'add #t) (put 'simplifiable 'sub #t) (put 'simplifiable 'mul #t) (put 'simplifiable 'div #t) (put 'simplifiable 'neg #t) (put 'simplifiable 'square-root #t) (put 'simplifiable 'sine #t) (put 'simplifiable 'cosine #t) (put 'simplifiable 'arctangent #t) (put 'simplifiable 'real-part #t) (put 'simplifiable 'imag-part #t) (put 'simplifiable 'magnitude #t) (put 'simplifiable 'angle #t) (let () (define (tag x) (attach-tag 'integer x)) (put 'add '(integer integer) (lambda (x y) (tag (+ x y)))) (put 'sub '(integer integer) (lambda (x y) (tag (- x y)))) (put 'mul '(integer integer) (lambda (x y) (tag (* x y)))) (put 'neg '(integer) (lambda (x) (tag (- x)))) (put 'equ? '(integer integer) =) (put '=zero? '(integer) zero?) (put 'raise '(integer) (lambda (n) (make-rational n 1))) (put 'make 'integer (lambda (n) (if (exact-integer? n) (tag n) (error "Attempted to make an integer with a non-integer" n))))) (define (make-integer n) ((get 'make 'integer) n)) (let () (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (if (and (exact-integer? n) (exact-integer? d)) (let ((g (gcd n d))) (cons (/ n g) (/ d g))) (error "Cannot construct a rational with non-exact numbers" n d))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (define (neg-rat x) (make-rat (- (numer x)) (denom x))) (define (=zero?-rat x) (zero? (numer x))) (define (raise-rat r) (make-real (exact->inexact (/ (numer r) (denom r))))) (define (project-rat r) (make-integer (truncate (/ (numer r) (denom r))))) (define (tag x) (attach-tag 'rational x)) (put 'numer '(rational) numer) (put 'denom '(rational) denom) (put 'raise '(rational) raise-rat) (put 'project '(rational) project-rat) (put '=zero? '(rational) =zero?-rat) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'neg '(rational) (lambda (x) (tag (neg-rat x)))) (put 'equ? '(rational rational) equal?) (put 'make 'rational (lambda (n d) (tag (make-rat n d))))) (define (make-rational n d) ((get 'make 'rational) n d)) (define (numer r) (apply-generic 'numer r)) (define (denom r) (apply-generic 'denom r)) (let () (define (tag x) (attach-tag 'real x)) (put 'add '(real real) (lambda (x y) (tag (+ x y)))) (put 'sub '(real real) (lambda (x y) (tag (- x y)))) (put 'mul '(real real) (lambda (x y) (tag (* x y)))) (put 'div '(real real) (lambda (x y) (tag (/ x y)))) (put 'neg '(real) (lambda (x) (tag (- x)))) (put 'sine '(real) (lambda (x) (tag (sin x)))) (put 'cosine '(real) (lambda (x) (tag (cos x)))) (put 'square-root '(real) (lambda (x) (tag (sqrt x)))) (put 'arctangent '(real real) (lambda (x y) (tag (atan x y)))) (put 'project '(real) (lambda (x) (make-rational (inexact->exact (truncate x)) 1))) (put 'equ? '(real real) =) (put '=zero? '(real) zero?) (put 'make 'real (lambda (x) (tag x)))) (define (make-real n) ((get 'make 'real) n)) And now , the polynomial package . First , the generic term - list operations . (define (make-term order coeff) (list order coeff)) (define (order term) (car term)) (define (coeff term) (cadr term)) (define (empty-termlist? term-list) (apply-generic 'empty-termlist? term-list)) (define (first-term term-list) (apply-generic 'first-term term-list)) (define (rest-terms term-list) (apply-generic 'rest-terms term-list)) (define (adjoin-term term term-list) (let ((proc (get 'adjoin-term (type-tag term-list)))) (if proc (proc term (contents term-list)) (error "No method for these types - ADJOIN-TERM" term-list)))) (let () (define (the-empty-termlist) '()) (define (empty-termlist? term-list) (null? term-list)) (define (first-term term-list) (car term-list)) (define (rest-terms term-list) (cdr term-list)) (define (adjoin-term term term-list) (cond ((=zero? (coeff term)) term-list) ((null? term-list) (list term)) ((> (order (car term-list)) (order term)) (cons (car term-list) (adjoin-term term (cdr term-list)))) ((= (order (car term-list)) (order term)) (adjoin-term (make-term (order term) (add (coeff term) (coeff (car term-list)))) (cdr term-list))) (else (cons term term-list)))) (define (tag x) (attach-tag 'sparse x)) (put 'empty-termlist? '(sparse) empty-termlist?) (put 'first-term '(sparse) first-term) (put 'rest-terms '(sparse) (lambda (l) (tag (rest-terms l)))) (put 'adjoin-term 'sparse (lambda (term term-list) (tag (adjoin-term term term-list)))) (put 'make 'sparse (lambda () (tag (the-empty-termlist))))) (define (the-empty-sparse-termlist) ((get 'make 'sparse))) (let () (define (the-empty-termlist) '()) (define (term-list-order term-list) (- (length term-list) 1)) (define (empty-termlist? term-list) (null? term-list)) (define (first-term term-list) (make-term (term-list-order term-list) (car term-list))) (define (rest-terms term-list) (cdr term-list)) (define (adjoin-term term term-list) (let ((term-list-order (term-list-order term-list)) (term-order (order term))) (cond ((=zero? (coeff term)) term-list) ((= term-list-order term-order) (cons (add (coeff term) (car term-list)) (cdr term-list))) ((< term-order term-list-order) (cons (car term-list) (adjoin-term term (cdr term-list)))) ((> term-order term-list-order) (adjoin-term term (cons (make-integer 0) term-list)))))) (define (tag x) (attach-tag 'dense x)) (put 'first-term '(dense) first-term) (put 'rest-terms '(dense) (lambda (l) (tag (rest-terms l)))) (put 'empty-termlist? '(dense) empty-termlist?) (put 'adjoin-term 'dense (lambda (term term-list) (tag (adjoin-term term term-list)))) (put 'make 'dense (lambda () (tag (the-empty-termlist))))) (define (the-empty-dense-termlist) ((get 'make 'dense))) (let () (define (make-poly variable term-list) (cons variable term-list)) (define (variable p) (car p)) (define (term-list p) (cdr p)) (define (same-variable? v1 v2) (and (variable? v1) (variable? v2) (eq? v1 v2))) (define (variable? x) (symbol? x)) (define (empty-termlist-of-type term-list) ((get 'make (type-tag term-list)))) (define (add-terms L1 L2) (cond ((empty-termlist? L1) L2) ((empty-termlist? L2) L1) (else (let ((t1 (first-term L1)) (t2 (first-term L2))) (cond ((> (order t1) (order t2)) (adjoin-term t1 (add-terms (rest-terms L1) L2))) ((< (order t1) (order t2)) (adjoin-term t2 (add-terms L1 (rest-terms L2)))) (else (adjoin-term (make-term (order t1) (add (coeff t1) (coeff t2))) (add-terms (rest-terms L1) (rest-terms L2))))))))) (define (mul-terms L1 L2) (if (empty-termlist? L1) (empty-termlist-of-type L1) (add-terms (mul-term-by-all-terms (first-term L1) L2) (mul-terms (rest-terms L1) L2)))) (define (mul-term-by-all-terms t1 L) (if (empty-termlist? L) (empty-termlist-of-type L) (let ((t2 (first-term L))) (adjoin-term (make-term (+ (order t1) (order t2)) (mul (coeff t1) (coeff t2))) (mul-term-by-all-terms t1 (rest-terms L)))))) (define (map-terms proc L) (if (empty-termlist? L) (empty-termlist-of-type L) (let ((first (first-term L)) (rest (rest-terms L))) (adjoin-term (make-term (order first) (proc (coeff first))) (map-terms proc rest))))) (define (neg-terms L) (map-terms neg L)) (define (add-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-poly (variable p1) (add-terms (term-list p1) (term-list p2))) (error "Polynomials not in same var - ADD-POLY" (list p1 p2)))) (define (mul-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-poly (variable p1) (mul-terms (term-list p1) (term-list p2))) (error "Polynomials not in same var - MUL-POLY" (list p1 p2)))) (define (sub-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (add-poly p1 (neg-poly p2)) (error "Polynomials not in same var - SUB-POLY" (list p1 p2)))) (define (neg-poly p) (make-poly (variable p) (neg-terms (term-list p)))) (define (make-const p n) (tag (make-poly (variable p) (adjoin-term (make-term 0 (make-integer n)) (empty-termlist-of-type (term-list p)))))) (define (tag p) (attach-tag 'polynomial p)) (put 'add '(polynomial polynomial) (lambda (p1 p2) (tag (add-poly p1 p2)))) (put 'sub '(polynomial polynomial) (lambda (p1 p2) (tag (sub-poly p1 p2)))) (put 'mul '(polynomial polynomial) (lambda (p1 p2) (tag (mul-poly p1 p2)))) (put '=zero? '(polynomial) (lambda (p) (empty-termlist? (term-list p)))) (put 'neg '(polynomial) (lambda (p) (tag (neg-poly p)))) (put 'add '(integer polynomial) (lambda (n p) (add (make-const p n) (tag p)))) (put 'mul '(integer polynomial) (lambda (n p) (mul (make-const p n) (tag p)))) (put 'add '(polynomial integer) (lambda (p n) (add (make-integer n) (tag p)))) (put 'mul '(polynomial integer) (lambda (p n) (mul (make-integer n) (tag p)))) (put 'make 'polynomial (lambda (var terms) (tag (make-poly var terms))))) (define (make-polynomial var terms) ((get 'make 'polynomial) var terms)) (define (apply-generic op . args) (define (applicable? args) (get op (map type-tag args))) (define (apply-generic-failed) (error "No method for these types - APPLY-GENERIC" (list op (map type-tag args)))) (define (all-of-same-type? args) (define (check rest) (cond ((null? rest) #t) ((same-type? (car args) (car rest)) (check (cdr rest))) (else #f))) (check args)) (define (of-same-type-and-raisable? args) (and (all-of-same-type? args) (raisable? (car args)))) (define (coercable-to-same-type? args) (and (= (length args) 2) (let ((type-a (type-tag (car args))) (type-b (type-tag (cadr args)))) (or (supertype? type-a type-b) (supertype? type-b type-a))))) (define (coerce-to-same-type args) (and (= (length args) 2) (let* ((a (car args)) (b (cadr args)) (type-a (type-tag a)) (type-b (type-tag b))) (cond ((same-type? a b) (list a b)) ((supertype? type-a type-b) (coerce-to-same-type (list (raise a) b))) ((supertype? type-b type-a) (coerce-to-same-type (list a (raise b)))) (else #f))))) (define (attempt-coercion args) (let ((number-of-arguments (length args))) (cond ((of-same-type-and-raisable? args) (try (map raise args))) ((coercable-to-same-type? args) (try (coerce-to-same-type args))) (else (apply-generic-failed))))) (define (try args) (if (applicable? args) (let ((result (apply (get op (map type-tag args)) (map contents args)))) (if (simplifiable? op) (simplify result) result)) (attempt-coercion args))) (try args))
6b79fb0ca6fadfac356562f9c907f2c8939aa6b7f1af16b0ab999b36f9fe2f6f
mmottl/gsl-ocaml
root.mli
gsl - ocaml - OCaml interface to GSL Copyright ( © ) 2002 - 2012 - Olivier Andrieu Distributed under the terms of the GPL version 3 * One dimensional Root - Finding module Bracket : sig type kind = | BISECTION | FALSEPOS | BRENT type t val make : kind -> Fun.gsl_fun -> float -> float -> t external name : t -> string = "ml_gsl_root_fsolver_name" external iterate : t -> unit = "ml_gsl_root_fsolver_iterate" external root : t -> float = "ml_gsl_root_fsolver_root" external interval : t -> float * float = "ml_gsl_root_fsolver_x_interv" end module Polish : sig type kind = | NEWTON | SECANT | STEFFENSON type t val make : kind -> Fun.gsl_fun_fdf -> float -> t external name : t -> string = "ml_gsl_root_fdfsolver_name" external iterate : t -> unit = "ml_gsl_root_fdfsolver_iterate" external root : t -> float = "ml_gsl_root_fdfsolver_root" end external test_interval : lo:float -> up:float -> epsabs:float -> epsrel:float -> bool = "ml_gsl_root_test_interval" external test_delta : x1:float -> x0:float -> epsabs:float -> epsrel:float -> bool = "ml_gsl_root_test_delta" external test_residual : f:float -> epsabs:float -> bool = "ml_gsl_root_test_residual"
null
https://raw.githubusercontent.com/mmottl/gsl-ocaml/76f8d93cccc1f23084f4a33d3e0a8f1289450580/src/root.mli
ocaml
gsl - ocaml - OCaml interface to GSL Copyright ( © ) 2002 - 2012 - Olivier Andrieu Distributed under the terms of the GPL version 3 * One dimensional Root - Finding module Bracket : sig type kind = | BISECTION | FALSEPOS | BRENT type t val make : kind -> Fun.gsl_fun -> float -> float -> t external name : t -> string = "ml_gsl_root_fsolver_name" external iterate : t -> unit = "ml_gsl_root_fsolver_iterate" external root : t -> float = "ml_gsl_root_fsolver_root" external interval : t -> float * float = "ml_gsl_root_fsolver_x_interv" end module Polish : sig type kind = | NEWTON | SECANT | STEFFENSON type t val make : kind -> Fun.gsl_fun_fdf -> float -> t external name : t -> string = "ml_gsl_root_fdfsolver_name" external iterate : t -> unit = "ml_gsl_root_fdfsolver_iterate" external root : t -> float = "ml_gsl_root_fdfsolver_root" end external test_interval : lo:float -> up:float -> epsabs:float -> epsrel:float -> bool = "ml_gsl_root_test_interval" external test_delta : x1:float -> x0:float -> epsabs:float -> epsrel:float -> bool = "ml_gsl_root_test_delta" external test_residual : f:float -> epsabs:float -> bool = "ml_gsl_root_test_residual"
99ecef1660a83cc5b8f50121ac1d1e1a3f736f2c242e777b88b2a5ed756b697f
mwunsch/overscan
info.rkt
#lang info (define scribblings '(("scribblings/overscan.scrbl" (multi-page))))
null
https://raw.githubusercontent.com/mwunsch/overscan/f198e6b4c1f64cf5720e66ab5ad27fdc4b9e67e9/overscan/info.rkt
racket
#lang info (define scribblings '(("scribblings/overscan.scrbl" (multi-page))))
8d04601d9678ecf9339211517c5ed8eb9523d7f73a52fba5473a7f0a483d0083
noinia/hgeometry
Internal.hs
# LANGUAGE Unsafe # module Geometry.Matrix.Internal where import Control.Lens (set) import Geometry.Vector import qualified Data.Vector.Fixed as FV -------------------------------------------------------------------------------- -- * Helper functions to easily create matrices -- | Creates a row with zeroes everywhere, except at position i, where the -- value is the supplied value. mkRow :: forall d r. (Arity d, Num r) => Int -> r -> Vector d r mkRow i x = set (FV.element i) x zero
null
https://raw.githubusercontent.com/noinia/hgeometry/89cd3d3109ec68f877bf8e34dc34b6df337a4ec1/hgeometry/src/Geometry/Matrix/Internal.hs
haskell
------------------------------------------------------------------------------ * Helper functions to easily create matrices | Creates a row with zeroes everywhere, except at position i, where the value is the supplied value.
# LANGUAGE Unsafe # module Geometry.Matrix.Internal where import Control.Lens (set) import Geometry.Vector import qualified Data.Vector.Fixed as FV mkRow :: forall d r. (Arity d, Num r) => Int -> r -> Vector d r mkRow i x = set (FV.element i) x zero
3891eae13a9419d979be1d4905d21a7177d0fdea7f104cda1d9fc3e801374e5b
arrdem/blather
user.clj
(ns user) (defn match [pattern string] (let [[string & groups] (re-find pattern string)] {:matched-text string :groups (into (sorted-map) vector (range 1 Long/MAX_VALUE) groups)}))
null
https://raw.githubusercontent.com/arrdem/blather/76fc860f26ae2fb7f0d2240da42cf85b0cb1169d/src/dev/clj/user.clj
clojure
(ns user) (defn match [pattern string] (let [[string & groups] (re-find pattern string)] {:matched-text string :groups (into (sorted-map) vector (range 1 Long/MAX_VALUE) groups)}))
0e74efbcc005ad1248bcf108687a0087f1c962598f0cad7cbb31906fc812247b
ntoronto/drbayes
store.rkt
#lang typed/racket/base (require racket/list racket/match racket/promise "bottom.rkt" "store-index.rkt" "../flonum.rkt" "../utils.rkt" "../untyped-utils.rkt") (provide (all-defined-out)) (struct Store ([random : (Maybe-Promise (U Prob Bad-Prob))] [branch : (Maybe-Promise (U Boolean Bottom))] [left : (Maybe-Promise Store)] [right : (Maybe-Promise Store)]) #:transparent) (define store? Store?) (: store-random (-> Store (U Prob Bad-Prob))) (: store-branch (-> Store (U Boolean Bottom))) (: store-left (-> Store Store)) (: store-right (-> Store Store)) (define (store-random t) (maybe-force (Store-random t))) (define (store-branch t) (maybe-force (Store-branch t))) (define (store-left t) (maybe-force (Store-left t))) (define (store-right t) (maybe-force (Store-right t))) (: store-random-list (-> Store (Listof (U Bad-Prob Prob)))) (define (store-random-list t) (let loop ([t t]) (match-define (Store x _ l r) t) (append (if (promise? x) empty (list x)) (if (promise? l) empty (loop l)) (if (promise? r) empty (loop r)))))
null
https://raw.githubusercontent.com/ntoronto/drbayes/e59eb7c7867118bf4c77ca903e133c7530e612a3/drbayes/private/set/store.rkt
racket
#lang typed/racket/base (require racket/list racket/match racket/promise "bottom.rkt" "store-index.rkt" "../flonum.rkt" "../utils.rkt" "../untyped-utils.rkt") (provide (all-defined-out)) (struct Store ([random : (Maybe-Promise (U Prob Bad-Prob))] [branch : (Maybe-Promise (U Boolean Bottom))] [left : (Maybe-Promise Store)] [right : (Maybe-Promise Store)]) #:transparent) (define store? Store?) (: store-random (-> Store (U Prob Bad-Prob))) (: store-branch (-> Store (U Boolean Bottom))) (: store-left (-> Store Store)) (: store-right (-> Store Store)) (define (store-random t) (maybe-force (Store-random t))) (define (store-branch t) (maybe-force (Store-branch t))) (define (store-left t) (maybe-force (Store-left t))) (define (store-right t) (maybe-force (Store-right t))) (: store-random-list (-> Store (Listof (U Bad-Prob Prob)))) (define (store-random-list t) (let loop ([t t]) (match-define (Store x _ l r) t) (append (if (promise? x) empty (list x)) (if (promise? l) empty (loop l)) (if (promise? r) empty (loop r)))))
0f51038a4511c5868dfae47fc48f03659fbd24352294f02b7bdddb1d74bde6bf
BranchTaken/Hemlock
rangeIntf.ml
(** Range interfaces. *) (** Range limit type. The distinction matters for minimal and maximal ranges. *) type 'a limit = * Half - open range limit . | Incl of 'a (** Full-open range limit. *) (** Range length type. Maximal full-open ranges may overflow the type being used to express length, which is encoded as [Overflow]. Furthermore the `nat` type may have infinite range length, which is also encoded as [Overflow]. *) type 'a length = | Overflow | Length of 'a (** Functor output signature for ranges. *) module type SRange = sig type t (** Container type. *) type elm (** Element type. *) type limit (** Limit type. *) type length (** Length type. *) val ( =:< ): elm -> elm -> t * [ base = : < past ] initializes a half - open range , i.e [ \[base .. past ) ] . No constraint is assumed regarding ordering of [ base ] and [ past ] , which among other behaviors enables ranges which wrap around . regarding ordering of [base] and [past], which among other behaviors enables ranges which wrap around. *) val ( =:= ): elm -> elm -> t * [ base = : = last ] initializes a full - open range , i.e [ \[base .. last\ ] ] . No constraint is assumed regarding ordering of [ base ] and [ last ] , which among other behaviors enables ranges which wrap around . assumed regarding ordering of [base] and [last], which among other behaviors enables ranges which wrap around. *) val base: t -> elm (** Base element in range. *) val limit: t -> limit * Range limit , i.e the index immediately past the last element in a half - open range , or the index of the last element in a full - open range . index of the last element in a full-open range. *) include ContainerIntf.SMonoIndex with type t := t with type elm := elm include ContainerIntf.SMonoMem with type t := t with type elm := elm include FormattableIntf.SMono with type t := t val length: t -> length (** Number of elements in range, or [Overflow] if a maximal full-open range. *) val length_hlt: t -> elm (** Number of elements in range. Halts on [Overflow]. *) end
null
https://raw.githubusercontent.com/BranchTaken/Hemlock/ed397cf3294ca397024e69eb3b1ed5f1db773db6/bootstrap/src/basis/rangeIntf.ml
ocaml
* Range interfaces. * Range limit type. The distinction matters for minimal and maximal ranges. * Full-open range limit. * Range length type. Maximal full-open ranges may overflow the type being used to express length, which is encoded as [Overflow]. Furthermore the `nat` type may have infinite range length, which is also encoded as [Overflow]. * Functor output signature for ranges. * Container type. * Element type. * Limit type. * Length type. * Base element in range. * Number of elements in range, or [Overflow] if a maximal full-open range. * Number of elements in range. Halts on [Overflow].
type 'a limit = * Half - open range limit . type 'a length = | Overflow | Length of 'a module type SRange = sig type t type elm type limit type length val ( =:< ): elm -> elm -> t * [ base = : < past ] initializes a half - open range , i.e [ \[base .. past ) ] . No constraint is assumed regarding ordering of [ base ] and [ past ] , which among other behaviors enables ranges which wrap around . regarding ordering of [base] and [past], which among other behaviors enables ranges which wrap around. *) val ( =:= ): elm -> elm -> t * [ base = : = last ] initializes a full - open range , i.e [ \[base .. last\ ] ] . No constraint is assumed regarding ordering of [ base ] and [ last ] , which among other behaviors enables ranges which wrap around . assumed regarding ordering of [base] and [last], which among other behaviors enables ranges which wrap around. *) val base: t -> elm val limit: t -> limit * Range limit , i.e the index immediately past the last element in a half - open range , or the index of the last element in a full - open range . index of the last element in a full-open range. *) include ContainerIntf.SMonoIndex with type t := t with type elm := elm include ContainerIntf.SMonoMem with type t := t with type elm := elm include FormattableIntf.SMono with type t := t val length: t -> length val length_hlt: t -> elm end
dce5db32798b8d4dd5430648819dad92c0e8eec2023ce5abf92055984698e70e
seckcoder/iu_c311
graph.rkt
#lang racket (provide anon-vtx wset-by-v vs cyclic->acyclic make-graph +bundle bundle bundle? pr-graph empty-visited visited? extend-visited bdl-by-v ) (define (union g vs) (let ((vs-list vs) (vs-set (list->set vs))) (let-values ([(vs-bdls g) (partition (lambda (bdl) (set-member? vs-set (bundle-v bdl))) g)]) (let* ((u (gensym)) (u-wset (set-subtract (foldl (match-lambda* [(list (bundle v wset vbset) u-wset) (set-union u-wset wset)]) (set) vs-bdls) vs-set)) (u-vbset (foldl (match-lambda* [(list (bundle v wset vbset) u-vbset) (set-union u-vbset vbset)]) (set) vs-bdls))) ; replace (+bundle1 (map (match-lambda [(bundle v wset vbset) (bundle v (let ((int-set (set-intersect wset vs-set))) (cond ((set-empty? int-set) wset) (else (set-add (set-subtract wset vs-set) u)))) vbset)]) g) (bundle u u-wset u-vbset)))))) (define (anon-vtx) (gensym)) ; v->w (define (wset-by-v g v) (bundle-wset (bdl-by-v g v))) ; all vtx of g (define (vs g) (map bundle-v g)) ; return an empty graph (define (empty-graph) '()) ; v: vertex ; wset: connected points ; vbset: information for vertex (struct bundle (v wset vbset) #:guard (lambda (v wset vbset tname) (if (and (symbol? v) (set? wset ) (set? vbset)) (values v wset vbset) (error tname "bad value for bundle")))) ; add a bundle to the graph ; if the v:ws is already exist in the graph, ; it will try to extend the bundle ; if the v:ws is not exist in the graph ; it will add a new bundle ; O(bundle-num) (define (+bundle g bdl) (match bdl [(bundle v wset vbset) (extend-bdl (+vtx g v) bdl)])) ; simply add the bundl to the graph assume the vtx is not exist in the graph (define (+bundle1 g bdl) (cons bdl g)) (define (rm-bdl-by-v g v) (filter (lambda (bdl) (not (eq? (bundle-v bdl) v))) g)) (define (bdl-by-v g v) (match (findf (lambda (bdl) (eq? (bundle-v bdl) v)) g) [#f (error 'bdl-by-v "can't find corresponding bundle of ~a" v)] [bdl bdl])) (define (+vtx g v) (match (findf (lambda (bdl) (eq? v (bundle-v bdl))) g) [#f (+vtx1 g v)] [(? bundle? bdl) g])) (define (+vtx1 g v) (cons (bundle v (set) (set)) g)) ; extend bdl of the corresponding bundle in graph (define (extend-bdl g bdl) (match bdl [(bundle v wset vbset) (map (match-lambda [(bundle v1 wset1 vbset1) (if (eq? v v1) (bundle v (set-union wset wset1) (set-union vbset vbset1)) (bundle v1 wset1 vbset1))]) g)])) (define (make-graph edges) (let ((g (empty-graph))) (foldl (match-lambda** [((list v (list ws ...)) g) (+bundle g (bundle v (list->set ws) (set v)))]) g edges))) (define (empty-visited) (set)) (define (visited? visited v) (set-member? visited v)) (define (extend-visited visited v) (set-add visited v)) (define (empty-path) '()) (define (extend-path path v) (cons v path)) (define (in-path? path v) (memq v path)) (define (path-take-since pred path) (reverse (dropf-right path (lambda (v) (not (pred v)))))) (struct cyclic (path visited)) (struct acyclic (visited)) (define (cyclic->acyclic g) (define (walk v g path visited-v) (cond ((visited? visited-v v) (acyclic visited-v)) (else (let ((visited-v (extend-visited visited-v v)) (path (extend-path path v))) (let ((w* (wset-by-v g v))) (let loop ((w* w*) (visited-v visited-v) (path path)) (cond ((set-empty? w*) (acyclic visited-v)) ((in-path? path (set-first w*)) (cyclic (path-take-since (lambda (v) (equal? v (set-first w*))) path) visited-v )) (else (match (walk (set-first w*) g path visited-v) [(? cyclic? c) c] [(acyclic visited-v) (loop (set-rest w*) visited-v path)]))))))))) (define (reformat-graph graph path) (union graph path)) (let loop ((v* (vs g)) (visited-v (empty-visited))) (cond ((null? v*) g) (else (match (walk (car v*) g (empty-path) visited-v) [(cyclic path visited-v) (cyclic->acyclic (reformat-graph g path))] [(acyclic visited-v) (loop (cdr v*) visited-v)]))))) (define (pr-graph g) (for-each (match-lambda [(bundle v wset vbset) (printf "~a -> ~a | ~a\n" v wset vbset)]) g)) (module+ test (define demo1 (make-graph '((a (b c)) (b (a)) (c ()) (d (e f g)) (e (f)) (f ()) (g ()) ))) ( pr - graph ) (pr-graph (cyclic->acyclic demo1)) )
null
https://raw.githubusercontent.com/seckcoder/iu_c311/a1215983b6ab08df32058ef1e089cb294419e567/racket/compiler/demos/parser/graph.rkt
racket
replace v->w all vtx of g return an empty graph v: vertex wset: connected points vbset: information for vertex add a bundle to the graph if the v:ws is already exist in the graph, it will try to extend the bundle if the v:ws is not exist in the graph it will add a new bundle O(bundle-num) simply add the bundl to the graph extend bdl of the corresponding bundle in graph
#lang racket (provide anon-vtx wset-by-v vs cyclic->acyclic make-graph +bundle bundle bundle? pr-graph empty-visited visited? extend-visited bdl-by-v ) (define (union g vs) (let ((vs-list vs) (vs-set (list->set vs))) (let-values ([(vs-bdls g) (partition (lambda (bdl) (set-member? vs-set (bundle-v bdl))) g)]) (let* ((u (gensym)) (u-wset (set-subtract (foldl (match-lambda* [(list (bundle v wset vbset) u-wset) (set-union u-wset wset)]) (set) vs-bdls) vs-set)) (u-vbset (foldl (match-lambda* [(list (bundle v wset vbset) u-vbset) (set-union u-vbset vbset)]) (set) vs-bdls))) (+bundle1 (map (match-lambda [(bundle v wset vbset) (bundle v (let ((int-set (set-intersect wset vs-set))) (cond ((set-empty? int-set) wset) (else (set-add (set-subtract wset vs-set) u)))) vbset)]) g) (bundle u u-wset u-vbset)))))) (define (anon-vtx) (gensym)) (define (wset-by-v g v) (bundle-wset (bdl-by-v g v))) (define (vs g) (map bundle-v g)) (define (empty-graph) '()) (struct bundle (v wset vbset) #:guard (lambda (v wset vbset tname) (if (and (symbol? v) (set? wset ) (set? vbset)) (values v wset vbset) (error tname "bad value for bundle")))) (define (+bundle g bdl) (match bdl [(bundle v wset vbset) (extend-bdl (+vtx g v) bdl)])) assume the vtx is not exist in the graph (define (+bundle1 g bdl) (cons bdl g)) (define (rm-bdl-by-v g v) (filter (lambda (bdl) (not (eq? (bundle-v bdl) v))) g)) (define (bdl-by-v g v) (match (findf (lambda (bdl) (eq? (bundle-v bdl) v)) g) [#f (error 'bdl-by-v "can't find corresponding bundle of ~a" v)] [bdl bdl])) (define (+vtx g v) (match (findf (lambda (bdl) (eq? v (bundle-v bdl))) g) [#f (+vtx1 g v)] [(? bundle? bdl) g])) (define (+vtx1 g v) (cons (bundle v (set) (set)) g)) (define (extend-bdl g bdl) (match bdl [(bundle v wset vbset) (map (match-lambda [(bundle v1 wset1 vbset1) (if (eq? v v1) (bundle v (set-union wset wset1) (set-union vbset vbset1)) (bundle v1 wset1 vbset1))]) g)])) (define (make-graph edges) (let ((g (empty-graph))) (foldl (match-lambda** [((list v (list ws ...)) g) (+bundle g (bundle v (list->set ws) (set v)))]) g edges))) (define (empty-visited) (set)) (define (visited? visited v) (set-member? visited v)) (define (extend-visited visited v) (set-add visited v)) (define (empty-path) '()) (define (extend-path path v) (cons v path)) (define (in-path? path v) (memq v path)) (define (path-take-since pred path) (reverse (dropf-right path (lambda (v) (not (pred v)))))) (struct cyclic (path visited)) (struct acyclic (visited)) (define (cyclic->acyclic g) (define (walk v g path visited-v) (cond ((visited? visited-v v) (acyclic visited-v)) (else (let ((visited-v (extend-visited visited-v v)) (path (extend-path path v))) (let ((w* (wset-by-v g v))) (let loop ((w* w*) (visited-v visited-v) (path path)) (cond ((set-empty? w*) (acyclic visited-v)) ((in-path? path (set-first w*)) (cyclic (path-take-since (lambda (v) (equal? v (set-first w*))) path) visited-v )) (else (match (walk (set-first w*) g path visited-v) [(? cyclic? c) c] [(acyclic visited-v) (loop (set-rest w*) visited-v path)]))))))))) (define (reformat-graph graph path) (union graph path)) (let loop ((v* (vs g)) (visited-v (empty-visited))) (cond ((null? v*) g) (else (match (walk (car v*) g (empty-path) visited-v) [(cyclic path visited-v) (cyclic->acyclic (reformat-graph g path))] [(acyclic visited-v) (loop (cdr v*) visited-v)]))))) (define (pr-graph g) (for-each (match-lambda [(bundle v wset vbset) (printf "~a -> ~a | ~a\n" v wset vbset)]) g)) (module+ test (define demo1 (make-graph '((a (b c)) (b (a)) (c ()) (d (e f g)) (e (f)) (f ()) (g ()) ))) ( pr - graph ) (pr-graph (cyclic->acyclic demo1)) )
61298060556fb49f144f53a4b59ae6c4f8296df42d93ff8d211d69f91765fffb
imitator-model-checker/imitator
TypeConstraintResolver.mli
open DiscreteType open FunctionSig open ParsingStructure type resolved_constraint = | Resolved_type_constraint of DiscreteType.var_type_discrete | Resolved_length_constraint of int val string_of_resolved_constraints : (constraint_name * resolved_constraint) list -> string val resolve_constraints : variable_infos -> signature_constraint -> signature -> (constraint_name * resolved_constraint) list * (constraint_name * resolved_constraint) list val signature_of_signature_constraint : (constraint_name, resolved_constraint) Hashtbl.t -> signature_constraint -> signature
null
https://raw.githubusercontent.com/imitator-model-checker/imitator/105408ae2bd8c3e3291f286e4d127defd492a58b/src/TypeConstraintResolver.mli
ocaml
open DiscreteType open FunctionSig open ParsingStructure type resolved_constraint = | Resolved_type_constraint of DiscreteType.var_type_discrete | Resolved_length_constraint of int val string_of_resolved_constraints : (constraint_name * resolved_constraint) list -> string val resolve_constraints : variable_infos -> signature_constraint -> signature -> (constraint_name * resolved_constraint) list * (constraint_name * resolved_constraint) list val signature_of_signature_constraint : (constraint_name, resolved_constraint) Hashtbl.t -> signature_constraint -> signature
6469d8f411e7f5d6aeb0c62f6161e0b69a14821e08d55fdb5845d6d487f81619
emilaxelsson/dino
Dino.hs
-- | The Dino language -- Dino is a tagless embedded DSL for numeric simple calculations . module Dino ( module Dino.Prelude , module Dino.Types , module Dino.Expression ) where import Dino.Prelude import Dino.Types import Dino.Expression import Dino.Interpretation ()
null
https://raw.githubusercontent.com/emilaxelsson/dino/3b3115a7fd694cbc3d4fca4d61b0166f4707173f/src/Dino.hs
haskell
| The Dino language
Dino is a tagless embedded DSL for numeric simple calculations . module Dino ( module Dino.Prelude , module Dino.Types , module Dino.Expression ) where import Dino.Prelude import Dino.Types import Dino.Expression import Dino.Interpretation ()
bf101d14543c0ed318a2bbbbdee54f9c4bf1bde7ccd2745d9b3a111e4b756d9f
Vaguery/klapaucius
vectorized_test.clj
(ns push.type.extra.vectorized_test (:require [push.type.item.scalar :as s] [push.type.item.string :as string] [push.type.item.char :as char] [push.type.item.complex :as cplx]) (:use midje.sweet) (:require [push.type.core :as core]) (:use [push.util.test-helpers]) (:use [push.type.item.vectorized]) ) (def vector-of-scalars (build-vectorized-type s/scalar-type)) (def vector-of-chars (build-vectorized-type char/char-type)) (def vector-of-strings (build-vectorized-type string/string-type)) (def vector-of-complexes (build-vectorized-type cplx/complex-type)) (fact "I can make a vector type out of :scalar" (:name vector-of-scalars) => :scalars) (fact "the :scalars type has the correct :recognizer" (core/recognize? vector-of-scalars [1 2 3]) => true (core/recognize? vector-of-scalars 99) => false (core/recognize? vector-of-scalars [1 2.2 3]) => true (core/recognize? vector-of-scalars [1/2 3e-4 5.6M 7]) => true (core/recognize? vector-of-scalars '(1 2 3)) => false (core/recognize? vector-of-scalars []) => false ) (fact ":scalars type has the expected :attributes" (:attributes vector-of-scalars) => (contains #{:equatable :movable :vector :visible})) (fact "vector-of-scalars knows the :equatable instructions" (keys (:instructions vector-of-scalars)) => (contains [:scalars-equal? :scalars-notequal?] :in-any-order :gaps-ok)) (fact "vector-of-scalars knows the :visible instructions" (keys (:instructions vector-of-scalars)) => (contains [:scalars-stackdepth :scalars-empty?] :in-any-order :gaps-ok)) (fact "vector-of-scalars knows the :movable instructions" (keys (:instructions vector-of-scalars)) => (contains [:scalars-shove :scalars-pop :scalars-dup :scalars-rotate :scalars-yank :scalars-yankdup :scalars-flush :scalars-swap] :in-any-order :gaps-ok)) (fact "vector-of-scalars knows the :printable instructions" (keys (:instructions vector-of-scalars)) => (contains [:scalars-print])) (fact "vector-of-scalars knows the :returnable instructions" (keys (:instructions vector-of-scalars)) => (contains [:scalars-return])) (fact "replacefirst helper substitutes an item at the first position it occurs (from a bug fix)" (replacefirst [1 2 3 4 3 2 1] 2 99) => [1 99 3 4 3 2 1] (replacefirst [1 2 3 4 3 2 1] 88 99) => [1 2 3 4 3 2 1] (replacefirst [1 2 3 4 3 2 1] 1 99) => [99 2 3 4 3 2 1] (replacefirst [1 2 3 4 3 2 7] 7 99) => [1 2 3 4 3 2 99] (replacefirst [1 2 3 4 3 2 7] 7 [6 6]) => [1 2 3 4 3 2 [6 6]] ;; it's generic ) (fact "x-sort-instruction only gets added to sortable root types" (keys (:instructions vector-of-scalars)) => (contains :scalars-sort) (keys (:instructions vector-of-complexes)) =not=> (contains :complexes-sort) ) (fact "x-order-instruction only gets added to sortable root types" (keys (:instructions vector-of-scalars)) => (contains :scalars-order) (keys (:instructions vector-of-complexes)) =not=> (contains :complexes-order) ) (fact "x-min-instruction only gets added to sortable root types" (keys (:instructions vector-of-scalars)) => (contains :scalars-min) (keys (:instructions vector-of-chars)) => (contains :chars-min) (keys (:instructions vector-of-strings)) => (contains :strings-min) (keys (:instructions vector-of-complexes)) =not=> (contains :complexes-min) ) (fact "x-max-instruction only gets added to sortable root types" (keys (:instructions vector-of-scalars)) => (contains :scalars-max) (keys (:instructions vector-of-chars)) => (contains :chars-max) (keys (:instructions vector-of-strings)) => (contains :strings-max) (keys (:instructions vector-of-complexes)) =not=> (contains :complexes-max) )
null
https://raw.githubusercontent.com/Vaguery/klapaucius/17b55eb76feaa520a85d4df93597cccffe6bdba4/test/push/type/extra/vectorized_test.clj
clojure
it's generic
(ns push.type.extra.vectorized_test (:require [push.type.item.scalar :as s] [push.type.item.string :as string] [push.type.item.char :as char] [push.type.item.complex :as cplx]) (:use midje.sweet) (:require [push.type.core :as core]) (:use [push.util.test-helpers]) (:use [push.type.item.vectorized]) ) (def vector-of-scalars (build-vectorized-type s/scalar-type)) (def vector-of-chars (build-vectorized-type char/char-type)) (def vector-of-strings (build-vectorized-type string/string-type)) (def vector-of-complexes (build-vectorized-type cplx/complex-type)) (fact "I can make a vector type out of :scalar" (:name vector-of-scalars) => :scalars) (fact "the :scalars type has the correct :recognizer" (core/recognize? vector-of-scalars [1 2 3]) => true (core/recognize? vector-of-scalars 99) => false (core/recognize? vector-of-scalars [1 2.2 3]) => true (core/recognize? vector-of-scalars [1/2 3e-4 5.6M 7]) => true (core/recognize? vector-of-scalars '(1 2 3)) => false (core/recognize? vector-of-scalars []) => false ) (fact ":scalars type has the expected :attributes" (:attributes vector-of-scalars) => (contains #{:equatable :movable :vector :visible})) (fact "vector-of-scalars knows the :equatable instructions" (keys (:instructions vector-of-scalars)) => (contains [:scalars-equal? :scalars-notequal?] :in-any-order :gaps-ok)) (fact "vector-of-scalars knows the :visible instructions" (keys (:instructions vector-of-scalars)) => (contains [:scalars-stackdepth :scalars-empty?] :in-any-order :gaps-ok)) (fact "vector-of-scalars knows the :movable instructions" (keys (:instructions vector-of-scalars)) => (contains [:scalars-shove :scalars-pop :scalars-dup :scalars-rotate :scalars-yank :scalars-yankdup :scalars-flush :scalars-swap] :in-any-order :gaps-ok)) (fact "vector-of-scalars knows the :printable instructions" (keys (:instructions vector-of-scalars)) => (contains [:scalars-print])) (fact "vector-of-scalars knows the :returnable instructions" (keys (:instructions vector-of-scalars)) => (contains [:scalars-return])) (fact "replacefirst helper substitutes an item at the first position it occurs (from a bug fix)" (replacefirst [1 2 3 4 3 2 1] 2 99) => [1 99 3 4 3 2 1] (replacefirst [1 2 3 4 3 2 1] 88 99) => [1 2 3 4 3 2 1] (replacefirst [1 2 3 4 3 2 1] 1 99) => [99 2 3 4 3 2 1] (replacefirst [1 2 3 4 3 2 7] 7 99) => [1 2 3 4 3 2 99] ) (fact "x-sort-instruction only gets added to sortable root types" (keys (:instructions vector-of-scalars)) => (contains :scalars-sort) (keys (:instructions vector-of-complexes)) =not=> (contains :complexes-sort) ) (fact "x-order-instruction only gets added to sortable root types" (keys (:instructions vector-of-scalars)) => (contains :scalars-order) (keys (:instructions vector-of-complexes)) =not=> (contains :complexes-order) ) (fact "x-min-instruction only gets added to sortable root types" (keys (:instructions vector-of-scalars)) => (contains :scalars-min) (keys (:instructions vector-of-chars)) => (contains :chars-min) (keys (:instructions vector-of-strings)) => (contains :strings-min) (keys (:instructions vector-of-complexes)) =not=> (contains :complexes-min) ) (fact "x-max-instruction only gets added to sortable root types" (keys (:instructions vector-of-scalars)) => (contains :scalars-max) (keys (:instructions vector-of-chars)) => (contains :chars-max) (keys (:instructions vector-of-strings)) => (contains :strings-max) (keys (:instructions vector-of-complexes)) =not=> (contains :complexes-max) )
98ad2da6ea17ed387ed74fb768045bb59a28ef2c04bf3ae3a5e5c610ec9db75a
pkamenarsky/synchron
DOM.hs
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # module Replica.DOM where import Control.Applicative (empty) import Control.Concurrent (newEmptyMVar, modifyMVar, newMVar, putMVar, takeMVar) import Control.Monad (void) import Replica.Props (Props(Props), Prop(PropText, PropBool, PropEvent, PropMap), key) import Data.Bifunctor (second) import Data.Monoid ((<>)) import qualified Data.Text as T import qualified Data.Map as M import Replica.VDOM (Attr(AText, ABool, AEvent, AMap), DOMEvent, VDOM(VNode, VText), fireEvent, defaultIndex) import qualified Replica.VDOM as R import Replica.VDOM.Types (DOMEvent(DOMEvent)) import qualified Replica.VDOM.Types as R import qualified Network.Wai.Handler.Warp as Warp import qualified Network.Wai.Handler.Replica as Replica import Network.WebSockets.Connection (defaultConnectionOptions) import Syn newtype HTML = HTML { runHTML :: Context HTML () -> R.HTML } deriving (Semigroup, Monoid) runReplica :: Syn Replica.DOM.HTML () -> IO () runReplica p = do let nid = NodeId 0 ctx <- newMVar (Just (0, p, E)) block <- newMVar () Warp.run 3985 $ Replica.app (defaultIndex "Synchron" []) defaultConnectionOptions Prelude.id () $ \() -> do takeMVar block modifyMVar ctx $ \ctx' -> case ctx' of Just (eid, p, v) -> do r <- stepAll mempty nid eid p v case r of (Left _, v', _) -> do pure (Nothing, Just (runHTML (foldV v') (Context nid ctx), (), \_ -> pure (pure ()))) (Right (eid', p'), v', _) -> do let html = runHTML (foldV v') (Context nid ctx) -- putStrLn (BC.unpack $ A.encode html) pure ( Just (eid', p', v') , Just (html, (), \re -> fmap (>> putMVar block()) $ fireEvent html (Replica.evtPath re) (Replica.evtType re) (DOMEvent $ Replica.evtEvent re)) ) Nothing -> pure (Nothing, Nothing) el' :: Maybe R.Namespace -> T.Text -> [Props a] -> [Syn HTML a] -> Syn HTML a el' ns e attrs children = do attrs' <- traverse toAttr attrs mapView (\children -> HTML $ \ctx -> [VNode e (M.fromList $ fmap (second ($ ctx) . fst) attrs') ns (runHTML children ctx)]) (children' attrs') where children' attrs' = case children <> concatMap snd attrs' of [] -> empty cs -> orr cs toAttr :: Props a -> Syn HTML ((T.Text, Context HTML () -> Attr), [Syn HTML a]) toAttr (Props k (PropText v)) = pure ((k, \_ -> AText v), []) toAttr (Props k (PropBool v)) = pure ((k, \_ -> ABool v), []) toAttr (Props k (PropEvent extract)) = local $ \e -> do pure ((k, \ctx -> AEvent $ \de -> void $ push ctx e de), [extract <$> await e]) toAttr (Props k (PropMap m)) = do m' <- mapM toAttr m pure ((k, \ctx -> AMap $ M.fromList $ fmap (second ($ ctx) . fst) m'), concatMap snd m') el :: T.Text -> [Props a] -> [Syn HTML a] -> Syn HTML a el = el' Nothing text :: T.Text -> Syn HTML a text txt = view (HTML $ \_ -> [VText txt]) >> forever -- | -US/docs/Web/HTML/Element/div div :: [Props a] -> [Syn HTML a] -> Syn HTML a div = el "div" -- | -US/docs/Web/HTML/Element/table table :: [Props a] -> [Syn HTML a] -> Syn HTML a table = el "table" -- | -US/docs/Web/HTML/Element/thead thead :: [Props a] -> [Syn HTML a] -> Syn HTML a thead = el "thead" -- | -US/docs/Web/HTML/Element/tbody tbody :: [Props a] -> [Syn HTML a] -> Syn HTML a tbody = el "tbody" -- | -US/docs/Web/HTML/Element/tr tr :: [Props a] -> [Syn HTML a] -> Syn HTML a tr = el "tr" -- | Contains `Key`, inteded to be used for child replacement patch -- -- <-US/docs/Web/HTML/Element/tr> trKeyed :: T.Text -> [Props a] -> [Syn HTML a] -> Syn HTML a trKeyed k props = el "tr" (key k:props) -- | -US/docs/Web/HTML/Element/th th :: [Props a] -> [Syn HTML a] -> Syn HTML a th = el "th" -- | -US/docs/Web/HTML/Element/td td :: [Props a] -> [Syn HTML a] -> Syn HTML a td = el "td" -- | -US/docs/Web/HTML/Element/tfoot tfoot :: [Props a] -> [Syn HTML a] -> Syn HTML a tfoot = el "tfoot" -- | -US/docs/Web/HTML/Element/section section :: [Props a] -> [Syn HTML a] -> Syn HTML a section = el "section" -- | -US/docs/Web/HTML/Element/header header :: [Props a] -> [Syn HTML a] -> Syn HTML a header = el "header" -- | -US/docs/Web/HTML/Element/footer footer :: [Props a] -> [Syn HTML a] -> Syn HTML a footer = el "footer" -- | -US/docs/Web/HTML/Element/button button :: [Props a] -> [Syn HTML a] -> Syn HTML a button = el "button" -- | -US/docs/Web/HTML/Element/form form :: [Props a] -> [Syn HTML a] -> Syn HTML a form = el "form" -- | -US/docs/Web/HTML/Element/p p :: [Props a] -> [Syn HTML a] -> Syn HTML a p = el "p" -- | -US/docs/Web/HTML/Element/s s :: [Props a] -> [Syn HTML a] -> Syn HTML a s = el "s" -- | -US/docs/Web/HTML/Element/ul ul :: [Props a] -> [Syn HTML a] -> Syn HTML a ul = el "ul" -- | -US/docs/Web/HTML/Element/span span :: [Props a] -> [Syn HTML a] -> Syn HTML a span = el "span" -- | -US/docs/Web/HTML/Element/strong strong :: [Props a] -> [Syn HTML a] -> Syn HTML a strong = el "strong" -- | -US/docs/Web/HTML/Element/li li :: [Props a] -> [Syn HTML a] -> Syn HTML a li = el "li" -- | Contains `Key`, inteded to be used for child replacement patch -- -- <-US/docs/Web/HTML/Element/li> -- liKeyed :: T.Text -> [Props a] -> [Syn HTML a] -> Syn HTML a liKeyed k props = el "li" (key k:props) -- | -US/docs/Web/HTML/Element/h1 h1 :: [Props a] -> [Syn HTML a] -> Syn HTML a h1 = el "h1" -- | -US/docs/Web/HTML/Element/h2 h2 :: [Props a] -> [Syn HTML a] -> Syn HTML a h2 = el "h2" -- | -US/docs/Web/HTML/Element/h3 h3 :: [Props a] -> [Syn HTML a] -> Syn HTML a h3 = el "h3" -- | -US/docs/Web/HTML/Element/h4 h4 :: [Props a] -> [Syn HTML a] -> Syn HTML a h4 = el "h4" -- | -US/docs/Web/HTML/Element/h5 h5 :: [Props a] -> [Syn HTML a] -> Syn HTML a h5 = el "h5" -- | -US/docs/Web/HTML/Element/h6 h6 :: [Props a] -> [Syn HTML a] -> Syn HTML a h6 = el "h6" -- | -US/docs/Web/HTML/Element/hr hr :: [Props a] -> Syn HTML a hr = flip (el "hr") [] -- | -US/docs/Web/HTML/Element/pre pre :: [Props a] -> [Syn HTML a] -> Syn HTML a pre = el "pre" -- | -US/docs/Web/HTML/Element/input input :: [Props a] -> Syn HTML a input = flip (el "input") [] -- | -US/docs/Web/HTML/Element/label label :: [Props a] -> [Syn HTML a] -> Syn HTML a label = el "label" -- | -US/docs/Web/HTML/Element/a a :: [Props a] -> [Syn HTML a] -> Syn HTML a a = el "a" -- | -US/docs/Web/HTML/Element/mark mark :: [Props a] -> [Syn HTML a] -> Syn HTML a mark = el "mark" | -US/docs/Web/HTML/Element/ruby ruby :: [Props a] -> [Syn HTML a] -> Syn HTML a ruby = el "ruby" -- | -US/docs/Web/HTML/Element/rt rt :: [Props a] -> [Syn HTML a] -> Syn HTML a rt = el "rt" -- | -US/docs/Web/HTML/Element/rp rp :: [Props a] -> [Syn HTML a] -> Syn HTML a rp = el "rp" -- | -US/docs/Web/HTML/Element/bdi bdi :: [Props a] -> [Syn HTML a] -> Syn HTML a bdi = el "bdi" -- | -US/docs/Web/HTML/Element/bdo bdo :: [Props a] -> [Syn HTML a] -> Syn HTML a bdo = el "bdo" | -US/docs/Web/HTML/Element/wbr wbr :: [Props a] -> Syn HTML a wbr = flip (el "wbr") [] -- | -US/docs/Web/HTML/Element/details details :: [Props a] -> [Syn HTML a] -> Syn HTML a details = el "details" -- | -US/docs/Web/HTML/Element/summary summary :: [Props a] -> [Syn HTML a] -> Syn HTML a summary = el "summary" -- | -US/docs/Web/HTML/Element/menuitem menuitem :: [Props a] -> [Syn HTML a] -> Syn HTML a menuitem = el "menuitem" | -US/docs/Web/HTML/Element/menu menu :: [Props a] -> [Syn HTML a] -> Syn HTML a menu = el "menu" -- | -US/docs/Web/HTML/Element/fieldset fieldset :: [Props a] -> [Syn HTML a] -> Syn HTML a fieldset = el "fieldset" -- | -US/docs/Web/HTML/Element/legend legend :: [Props a] -> [Syn HTML a] -> Syn HTML a legend = el "legend" -- | -US/docs/Web/HTML/Element/datalist datalist :: [Props a] -> [Syn HTML a] -> Syn HTML a datalist = el "datalist" -- | -US/docs/Web/HTML/Element/optgroup optgroup :: [Props a] -> [Syn HTML a] -> Syn HTML a optgroup = el "optgroup" | keygen :: [Props a] -> [Syn HTML a] -> Syn HTML a keygen = el "keygen" -- | -US/docs/Web/HTML/Element/output output :: [Props a] -> [Syn HTML a] -> Syn HTML a output = el "output" -- | -US/docs/Web/HTML/Element/progress progress :: [Props a] -> [Syn HTML a] -> Syn HTML a progress = el "progress" -- | -US/docs/Web/HTML/Element/meter meter :: [Props a] -> [Syn HTML a] -> Syn HTML a meter = el "meter" -- | -US/docs/Web/HTML/Element/center center :: [Props a] -> [Syn HTML a] -> Syn HTML a center = el "center" -- | -US/docs/Web/HTML/Element/audio audio :: [Props a] -> [Syn HTML a] -> Syn HTML a audio = el "audio" -- | -US/docs/Web/HTML/Element/video video :: [Props a] -> [Syn HTML a] -> Syn HTML a video = el "video" -- | -US/docs/Web/HTML/Element/source source :: [Props a] -> Syn HTML a source = flip (el "source") [] -- | -US/docs/Web/HTML/Element/track track :: [Props a] -> Syn HTML a track = flip (el "track") [] -- | -US/docs/Web/HTML/Element/embed embed :: [Props a] -> Syn HTML a embed = flip (el "embed") [] -- | -US/docs/Web/HTML/Element/object object :: [Props a] -> [Syn HTML a] -> Syn HTML a object = el "object" -- | -US/docs/Web/HTML/Element/param param :: [Props a] -> Syn HTML a param = flip (el "param") [] -- | -US/docs/Web/HTML/Element/ins ins :: [Props a] -> [Syn HTML a] -> Syn HTML a ins = el "ins" -- | -US/docs/Web/HTML/Element/del del :: [Props a] -> [Syn HTML a] -> Syn HTML a del = el "del" -- | -US/docs/Web/HTML/Element/small small :: [Props a] -> [Syn HTML a] -> Syn HTML a small = el "small" -- | -US/docs/Web/HTML/Element/cite cite :: [Props a] -> [Syn HTML a] -> Syn HTML a cite = el "cite" -- | -US/docs/Web/HTML/Element/dfn dfn :: [Props a] -> [Syn HTML a] -> Syn HTML a dfn = el "dfn" -- | -US/docs/Web/HTML/Element/abbr abbr :: [Props a] -> [Syn HTML a] -> Syn HTML a abbr = el "abbr" -- | -US/docs/Web/HTML/Element/time time :: [Props a] -> [Syn HTML a] -> Syn HTML a time = el "time" -- | -US/docs/Web/HTML/Element/var var :: [Props a] -> [Syn HTML a] -> Syn HTML a var = el "var" -- | -US/docs/Web/HTML/Element/samp samp :: [Props a] -> [Syn HTML a] -> Syn HTML a samp = el "samp" -- | -US/docs/Web/HTML/Element/kbd kbd :: [Props a] -> [Syn HTML a] -> Syn HTML a kbd = el "kbd" -- | -US/docs/Web/HTML/Element/caption caption :: [Props a] -> [Syn HTML a] -> Syn HTML a caption = el "caption" -- | -US/docs/Web/HTML/Element/colgroup colgroup :: [Props a] -> [Syn HTML a] -> Syn HTML a colgroup = el "colgroup" | col :: [Props a] -> Syn HTML a col = flip (el "col") [] -- | -US/docs/Web/HTML/Element/nav nav :: [Props a] -> [Syn HTML a] -> Syn HTML a nav = el "nav" -- | -US/docs/Web/HTML/Element/article article :: [Props a] -> [Syn HTML a] -> Syn HTML a article = el "article" -- | -US/docs/Web/HTML/Element/aside aside :: [Props a] -> [Syn HTML a] -> Syn HTML a aside = el "aside" -- | -US/docs/Web/HTML/Element/address address :: [Props a] -> [Syn HTML a] -> Syn HTML a address = el "address" -- | -US/docs/Web/HTML/Element/main main_ :: [Props a] -> [Syn HTML a] -> Syn HTML a main_ = el "main" | -US/docs/Web/HTML/Element/body body :: [Props a] -> [Syn HTML a] -> Syn HTML a body = el "body" -- | -US/docs/Web/HTML/Element/figure figure :: [Props a] -> [Syn HTML a] -> Syn HTML a figure = el "figure" -- | -US/docs/Web/HTML/Element/figcaption figcaption :: [Props a] -> [Syn HTML a] -> Syn HTML a figcaption = el "figcaption" -- | -US/docs/Web/HTML/Element/dl dl :: [Props a] -> [Syn HTML a] -> Syn HTML a dl = el "dl" -- | -US/docs/Web/HTML/Element/dt dt :: [Props a] -> [Syn HTML a] -> Syn HTML a dt = el "dt" -- | -US/docs/Web/HTML/Element/dd dd :: [Props a] -> [Syn HTML a] -> Syn HTML a dd = el "dd" -- | -US/docs/Web/HTML/Element/img img :: [Props a] -> Syn HTML a img = flip (el "img") [] -- | -US/docs/Web/HTML/Element/iframe iframe :: [Props a] -> [Syn HTML a] -> Syn HTML a iframe = el "iframe" -- | -US/docs/Web/HTML/Element/canvas canvas :: [Props a] -> [Syn HTML a] -> Syn HTML a canvas = el "canvas" -- | -US/docs/Web/HTML/Element/math math :: [Props a] -> [Syn HTML a] -> Syn HTML a math = el "math" -- | -US/docs/Web/HTML/Element/select select :: [Props a] -> [Syn HTML a] -> Syn HTML a select = el "select" -- | -US/docs/Web/HTML/Element/option option :: [Props a] -> [Syn HTML a] -> Syn HTML a option = el "option" -- | -US/docs/Web/HTML/Element/textarea textarea :: [Props a] -> [Syn HTML a] -> Syn HTML a textarea = el "textarea" -- | -US/docs/Web/HTML/Element/sub sub :: [Props a] -> [Syn HTML a] -> Syn HTML a sub = el "sub" -- | -US/docs/Web/HTML/Element/sup sup :: [Props a] -> [Syn HTML a] -> Syn HTML a sup = el "sup" -- | -US/docs/Web/HTML/Element/br br :: [Props a] -> Syn HTML a br = flip (el "br") [] -- | -US/docs/Web/HTML/Element/ol ol :: [Props a] -> [Syn HTML a] -> Syn HTML a ol = el "ol" -- | -US/docs/Web/HTML/Element/blockquote blockquote :: [Props a] -> [Syn HTML a] -> Syn HTML a blockquote = el "blockquote" -- | -US/docs/Web/HTML/Element/code code :: [Props a] -> [Syn HTML a] -> Syn HTML a code = el "code" -- | -US/docs/Web/HTML/Element/em em :: [Props a] -> [Syn HTML a] -> Syn HTML a em = el "em" -- | -US/docs/Web/HTML/Element/i i :: [Props a] -> [Syn HTML a] -> Syn HTML a i = el "i" -- | -US/docs/Web/HTML/Element/b b :: [Props a] -> [Syn HTML a] -> Syn HTML a b = el "b" -- | -US/docs/Web/HTML/Element/u u :: [Props a] -> [Syn HTML a] -> Syn HTML a u = el "u" -- | -US/docs/Web/HTML/Element/q q :: [Props a] -> [Syn HTML a] -> Syn HTML a q = el "q" | -US/docs/Web/HTML/Element/script script :: [Props a] -> [Syn HTML a] -> Syn HTML a script = el "script" -- | -US/docs/Web/HTML/Element/link link :: [Props a] -> Syn HTML a link = flip (el "link") []
null
https://raw.githubusercontent.com/pkamenarsky/synchron/8fa21f586b974da830c202b58a46a652176a6933/src/Replica/DOM.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE FlexibleContexts # # LANGUAGE OverloadedStrings # putStrLn (BC.unpack $ A.encode html) | -US/docs/Web/HTML/Element/div | -US/docs/Web/HTML/Element/table | -US/docs/Web/HTML/Element/thead | -US/docs/Web/HTML/Element/tbody | -US/docs/Web/HTML/Element/tr | Contains `Key`, inteded to be used for child replacement patch <-US/docs/Web/HTML/Element/tr> | -US/docs/Web/HTML/Element/th | -US/docs/Web/HTML/Element/td | -US/docs/Web/HTML/Element/tfoot | -US/docs/Web/HTML/Element/section | -US/docs/Web/HTML/Element/header | -US/docs/Web/HTML/Element/footer | -US/docs/Web/HTML/Element/button | -US/docs/Web/HTML/Element/form | -US/docs/Web/HTML/Element/p | -US/docs/Web/HTML/Element/s | -US/docs/Web/HTML/Element/ul | -US/docs/Web/HTML/Element/span | -US/docs/Web/HTML/Element/strong | -US/docs/Web/HTML/Element/li | Contains `Key`, inteded to be used for child replacement patch <-US/docs/Web/HTML/Element/li> | -US/docs/Web/HTML/Element/h1 | -US/docs/Web/HTML/Element/h2 | -US/docs/Web/HTML/Element/h3 | -US/docs/Web/HTML/Element/h4 | -US/docs/Web/HTML/Element/h5 | -US/docs/Web/HTML/Element/h6 | -US/docs/Web/HTML/Element/hr | -US/docs/Web/HTML/Element/pre | -US/docs/Web/HTML/Element/input | -US/docs/Web/HTML/Element/label | -US/docs/Web/HTML/Element/a | -US/docs/Web/HTML/Element/mark | -US/docs/Web/HTML/Element/rt | -US/docs/Web/HTML/Element/rp | -US/docs/Web/HTML/Element/bdi | -US/docs/Web/HTML/Element/bdo | -US/docs/Web/HTML/Element/details | -US/docs/Web/HTML/Element/summary | -US/docs/Web/HTML/Element/menuitem | -US/docs/Web/HTML/Element/fieldset | -US/docs/Web/HTML/Element/legend | -US/docs/Web/HTML/Element/datalist | -US/docs/Web/HTML/Element/optgroup | -US/docs/Web/HTML/Element/output | -US/docs/Web/HTML/Element/progress | -US/docs/Web/HTML/Element/meter | -US/docs/Web/HTML/Element/center | -US/docs/Web/HTML/Element/audio | -US/docs/Web/HTML/Element/video | -US/docs/Web/HTML/Element/source | -US/docs/Web/HTML/Element/track | -US/docs/Web/HTML/Element/embed | -US/docs/Web/HTML/Element/object | -US/docs/Web/HTML/Element/param | -US/docs/Web/HTML/Element/ins | -US/docs/Web/HTML/Element/del | -US/docs/Web/HTML/Element/small | -US/docs/Web/HTML/Element/cite | -US/docs/Web/HTML/Element/dfn | -US/docs/Web/HTML/Element/abbr | -US/docs/Web/HTML/Element/time | -US/docs/Web/HTML/Element/var | -US/docs/Web/HTML/Element/samp | -US/docs/Web/HTML/Element/kbd | -US/docs/Web/HTML/Element/caption | -US/docs/Web/HTML/Element/colgroup | -US/docs/Web/HTML/Element/nav | -US/docs/Web/HTML/Element/article | -US/docs/Web/HTML/Element/aside | -US/docs/Web/HTML/Element/address | -US/docs/Web/HTML/Element/main | -US/docs/Web/HTML/Element/figure | -US/docs/Web/HTML/Element/figcaption | -US/docs/Web/HTML/Element/dl | -US/docs/Web/HTML/Element/dt | -US/docs/Web/HTML/Element/dd | -US/docs/Web/HTML/Element/img | -US/docs/Web/HTML/Element/iframe | -US/docs/Web/HTML/Element/canvas | -US/docs/Web/HTML/Element/math | -US/docs/Web/HTML/Element/select | -US/docs/Web/HTML/Element/option | -US/docs/Web/HTML/Element/textarea | -US/docs/Web/HTML/Element/sub | -US/docs/Web/HTML/Element/sup | -US/docs/Web/HTML/Element/br | -US/docs/Web/HTML/Element/ol | -US/docs/Web/HTML/Element/blockquote | -US/docs/Web/HTML/Element/code | -US/docs/Web/HTML/Element/em | -US/docs/Web/HTML/Element/i | -US/docs/Web/HTML/Element/b | -US/docs/Web/HTML/Element/u | -US/docs/Web/HTML/Element/q | -US/docs/Web/HTML/Element/link
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ScopedTypeVariables # module Replica.DOM where import Control.Applicative (empty) import Control.Concurrent (newEmptyMVar, modifyMVar, newMVar, putMVar, takeMVar) import Control.Monad (void) import Replica.Props (Props(Props), Prop(PropText, PropBool, PropEvent, PropMap), key) import Data.Bifunctor (second) import Data.Monoid ((<>)) import qualified Data.Text as T import qualified Data.Map as M import Replica.VDOM (Attr(AText, ABool, AEvent, AMap), DOMEvent, VDOM(VNode, VText), fireEvent, defaultIndex) import qualified Replica.VDOM as R import Replica.VDOM.Types (DOMEvent(DOMEvent)) import qualified Replica.VDOM.Types as R import qualified Network.Wai.Handler.Warp as Warp import qualified Network.Wai.Handler.Replica as Replica import Network.WebSockets.Connection (defaultConnectionOptions) import Syn newtype HTML = HTML { runHTML :: Context HTML () -> R.HTML } deriving (Semigroup, Monoid) runReplica :: Syn Replica.DOM.HTML () -> IO () runReplica p = do let nid = NodeId 0 ctx <- newMVar (Just (0, p, E)) block <- newMVar () Warp.run 3985 $ Replica.app (defaultIndex "Synchron" []) defaultConnectionOptions Prelude.id () $ \() -> do takeMVar block modifyMVar ctx $ \ctx' -> case ctx' of Just (eid, p, v) -> do r <- stepAll mempty nid eid p v case r of (Left _, v', _) -> do pure (Nothing, Just (runHTML (foldV v') (Context nid ctx), (), \_ -> pure (pure ()))) (Right (eid', p'), v', _) -> do let html = runHTML (foldV v') (Context nid ctx) pure ( Just (eid', p', v') , Just (html, (), \re -> fmap (>> putMVar block()) $ fireEvent html (Replica.evtPath re) (Replica.evtType re) (DOMEvent $ Replica.evtEvent re)) ) Nothing -> pure (Nothing, Nothing) el' :: Maybe R.Namespace -> T.Text -> [Props a] -> [Syn HTML a] -> Syn HTML a el' ns e attrs children = do attrs' <- traverse toAttr attrs mapView (\children -> HTML $ \ctx -> [VNode e (M.fromList $ fmap (second ($ ctx) . fst) attrs') ns (runHTML children ctx)]) (children' attrs') where children' attrs' = case children <> concatMap snd attrs' of [] -> empty cs -> orr cs toAttr :: Props a -> Syn HTML ((T.Text, Context HTML () -> Attr), [Syn HTML a]) toAttr (Props k (PropText v)) = pure ((k, \_ -> AText v), []) toAttr (Props k (PropBool v)) = pure ((k, \_ -> ABool v), []) toAttr (Props k (PropEvent extract)) = local $ \e -> do pure ((k, \ctx -> AEvent $ \de -> void $ push ctx e de), [extract <$> await e]) toAttr (Props k (PropMap m)) = do m' <- mapM toAttr m pure ((k, \ctx -> AMap $ M.fromList $ fmap (second ($ ctx) . fst) m'), concatMap snd m') el :: T.Text -> [Props a] -> [Syn HTML a] -> Syn HTML a el = el' Nothing text :: T.Text -> Syn HTML a text txt = view (HTML $ \_ -> [VText txt]) >> forever div :: [Props a] -> [Syn HTML a] -> Syn HTML a div = el "div" table :: [Props a] -> [Syn HTML a] -> Syn HTML a table = el "table" thead :: [Props a] -> [Syn HTML a] -> Syn HTML a thead = el "thead" tbody :: [Props a] -> [Syn HTML a] -> Syn HTML a tbody = el "tbody" tr :: [Props a] -> [Syn HTML a] -> Syn HTML a tr = el "tr" trKeyed :: T.Text -> [Props a] -> [Syn HTML a] -> Syn HTML a trKeyed k props = el "tr" (key k:props) th :: [Props a] -> [Syn HTML a] -> Syn HTML a th = el "th" td :: [Props a] -> [Syn HTML a] -> Syn HTML a td = el "td" tfoot :: [Props a] -> [Syn HTML a] -> Syn HTML a tfoot = el "tfoot" section :: [Props a] -> [Syn HTML a] -> Syn HTML a section = el "section" header :: [Props a] -> [Syn HTML a] -> Syn HTML a header = el "header" footer :: [Props a] -> [Syn HTML a] -> Syn HTML a footer = el "footer" button :: [Props a] -> [Syn HTML a] -> Syn HTML a button = el "button" form :: [Props a] -> [Syn HTML a] -> Syn HTML a form = el "form" p :: [Props a] -> [Syn HTML a] -> Syn HTML a p = el "p" s :: [Props a] -> [Syn HTML a] -> Syn HTML a s = el "s" ul :: [Props a] -> [Syn HTML a] -> Syn HTML a ul = el "ul" span :: [Props a] -> [Syn HTML a] -> Syn HTML a span = el "span" strong :: [Props a] -> [Syn HTML a] -> Syn HTML a strong = el "strong" li :: [Props a] -> [Syn HTML a] -> Syn HTML a li = el "li" liKeyed :: T.Text -> [Props a] -> [Syn HTML a] -> Syn HTML a liKeyed k props = el "li" (key k:props) h1 :: [Props a] -> [Syn HTML a] -> Syn HTML a h1 = el "h1" h2 :: [Props a] -> [Syn HTML a] -> Syn HTML a h2 = el "h2" h3 :: [Props a] -> [Syn HTML a] -> Syn HTML a h3 = el "h3" h4 :: [Props a] -> [Syn HTML a] -> Syn HTML a h4 = el "h4" h5 :: [Props a] -> [Syn HTML a] -> Syn HTML a h5 = el "h5" h6 :: [Props a] -> [Syn HTML a] -> Syn HTML a h6 = el "h6" hr :: [Props a] -> Syn HTML a hr = flip (el "hr") [] pre :: [Props a] -> [Syn HTML a] -> Syn HTML a pre = el "pre" input :: [Props a] -> Syn HTML a input = flip (el "input") [] label :: [Props a] -> [Syn HTML a] -> Syn HTML a label = el "label" a :: [Props a] -> [Syn HTML a] -> Syn HTML a a = el "a" mark :: [Props a] -> [Syn HTML a] -> Syn HTML a mark = el "mark" | -US/docs/Web/HTML/Element/ruby ruby :: [Props a] -> [Syn HTML a] -> Syn HTML a ruby = el "ruby" rt :: [Props a] -> [Syn HTML a] -> Syn HTML a rt = el "rt" rp :: [Props a] -> [Syn HTML a] -> Syn HTML a rp = el "rp" bdi :: [Props a] -> [Syn HTML a] -> Syn HTML a bdi = el "bdi" bdo :: [Props a] -> [Syn HTML a] -> Syn HTML a bdo = el "bdo" | -US/docs/Web/HTML/Element/wbr wbr :: [Props a] -> Syn HTML a wbr = flip (el "wbr") [] details :: [Props a] -> [Syn HTML a] -> Syn HTML a details = el "details" summary :: [Props a] -> [Syn HTML a] -> Syn HTML a summary = el "summary" menuitem :: [Props a] -> [Syn HTML a] -> Syn HTML a menuitem = el "menuitem" | -US/docs/Web/HTML/Element/menu menu :: [Props a] -> [Syn HTML a] -> Syn HTML a menu = el "menu" fieldset :: [Props a] -> [Syn HTML a] -> Syn HTML a fieldset = el "fieldset" legend :: [Props a] -> [Syn HTML a] -> Syn HTML a legend = el "legend" datalist :: [Props a] -> [Syn HTML a] -> Syn HTML a datalist = el "datalist" optgroup :: [Props a] -> [Syn HTML a] -> Syn HTML a optgroup = el "optgroup" | keygen :: [Props a] -> [Syn HTML a] -> Syn HTML a keygen = el "keygen" output :: [Props a] -> [Syn HTML a] -> Syn HTML a output = el "output" progress :: [Props a] -> [Syn HTML a] -> Syn HTML a progress = el "progress" meter :: [Props a] -> [Syn HTML a] -> Syn HTML a meter = el "meter" center :: [Props a] -> [Syn HTML a] -> Syn HTML a center = el "center" audio :: [Props a] -> [Syn HTML a] -> Syn HTML a audio = el "audio" video :: [Props a] -> [Syn HTML a] -> Syn HTML a video = el "video" source :: [Props a] -> Syn HTML a source = flip (el "source") [] track :: [Props a] -> Syn HTML a track = flip (el "track") [] embed :: [Props a] -> Syn HTML a embed = flip (el "embed") [] object :: [Props a] -> [Syn HTML a] -> Syn HTML a object = el "object" param :: [Props a] -> Syn HTML a param = flip (el "param") [] ins :: [Props a] -> [Syn HTML a] -> Syn HTML a ins = el "ins" del :: [Props a] -> [Syn HTML a] -> Syn HTML a del = el "del" small :: [Props a] -> [Syn HTML a] -> Syn HTML a small = el "small" cite :: [Props a] -> [Syn HTML a] -> Syn HTML a cite = el "cite" dfn :: [Props a] -> [Syn HTML a] -> Syn HTML a dfn = el "dfn" abbr :: [Props a] -> [Syn HTML a] -> Syn HTML a abbr = el "abbr" time :: [Props a] -> [Syn HTML a] -> Syn HTML a time = el "time" var :: [Props a] -> [Syn HTML a] -> Syn HTML a var = el "var" samp :: [Props a] -> [Syn HTML a] -> Syn HTML a samp = el "samp" kbd :: [Props a] -> [Syn HTML a] -> Syn HTML a kbd = el "kbd" caption :: [Props a] -> [Syn HTML a] -> Syn HTML a caption = el "caption" colgroup :: [Props a] -> [Syn HTML a] -> Syn HTML a colgroup = el "colgroup" | col :: [Props a] -> Syn HTML a col = flip (el "col") [] nav :: [Props a] -> [Syn HTML a] -> Syn HTML a nav = el "nav" article :: [Props a] -> [Syn HTML a] -> Syn HTML a article = el "article" aside :: [Props a] -> [Syn HTML a] -> Syn HTML a aside = el "aside" address :: [Props a] -> [Syn HTML a] -> Syn HTML a address = el "address" main_ :: [Props a] -> [Syn HTML a] -> Syn HTML a main_ = el "main" | -US/docs/Web/HTML/Element/body body :: [Props a] -> [Syn HTML a] -> Syn HTML a body = el "body" figure :: [Props a] -> [Syn HTML a] -> Syn HTML a figure = el "figure" figcaption :: [Props a] -> [Syn HTML a] -> Syn HTML a figcaption = el "figcaption" dl :: [Props a] -> [Syn HTML a] -> Syn HTML a dl = el "dl" dt :: [Props a] -> [Syn HTML a] -> Syn HTML a dt = el "dt" dd :: [Props a] -> [Syn HTML a] -> Syn HTML a dd = el "dd" img :: [Props a] -> Syn HTML a img = flip (el "img") [] iframe :: [Props a] -> [Syn HTML a] -> Syn HTML a iframe = el "iframe" canvas :: [Props a] -> [Syn HTML a] -> Syn HTML a canvas = el "canvas" math :: [Props a] -> [Syn HTML a] -> Syn HTML a math = el "math" select :: [Props a] -> [Syn HTML a] -> Syn HTML a select = el "select" option :: [Props a] -> [Syn HTML a] -> Syn HTML a option = el "option" textarea :: [Props a] -> [Syn HTML a] -> Syn HTML a textarea = el "textarea" sub :: [Props a] -> [Syn HTML a] -> Syn HTML a sub = el "sub" sup :: [Props a] -> [Syn HTML a] -> Syn HTML a sup = el "sup" br :: [Props a] -> Syn HTML a br = flip (el "br") [] ol :: [Props a] -> [Syn HTML a] -> Syn HTML a ol = el "ol" blockquote :: [Props a] -> [Syn HTML a] -> Syn HTML a blockquote = el "blockquote" code :: [Props a] -> [Syn HTML a] -> Syn HTML a code = el "code" em :: [Props a] -> [Syn HTML a] -> Syn HTML a em = el "em" i :: [Props a] -> [Syn HTML a] -> Syn HTML a i = el "i" b :: [Props a] -> [Syn HTML a] -> Syn HTML a b = el "b" u :: [Props a] -> [Syn HTML a] -> Syn HTML a u = el "u" q :: [Props a] -> [Syn HTML a] -> Syn HTML a q = el "q" | -US/docs/Web/HTML/Element/script script :: [Props a] -> [Syn HTML a] -> Syn HTML a script = el "script" link :: [Props a] -> Syn HTML a link = flip (el "link") []
8353e8f7888ad9ae45c9fe281b423fb584d3d5039c91ec6a2456a69cc92dd020
5HT/ant
Bitmap.ml
type bitmap = { bm_width : int; bm_height : int; bm_bytes_per_row : int; bm_data : string }; value make width height = { bm_width = width; bm_height = height; bm_bytes_per_row = (width + 7) / 8; bm_data = String.make (((width + 7) / 8) * height) '\000' }; value get_index bm x y = y * bm.bm_bytes_per_row + x / 8; value get_bit x = (1 lsl (7 - (x land 7))); value unsafe_point bm x y = do { let i = get_index bm x y; Char.code bm.bm_data.[i] land get_bit x <> 0 }; value unsafe_set_point bm x y = do { let i = get_index bm x y; Bytes.set (Bytes.of_string bm.bm_data) i (Char.unsafe_chr (Char.code bm.bm_data.[i] lor get_bit x)) }; value unsafe_unset_point bm x y = do { let i = get_index bm x y; Bytes.set (Bytes.of_string bm.bm_data) i (Char.unsafe_chr (Char.code bm.bm_data.[i] land (lnot (get_bit x)))) }; value point bm x y = do { if 0 <= x && x < bm.bm_width && 0 <= y && y < bm.bm_height then unsafe_point bm x y else False }; value set_point bm x y = do { if 0 <= x && x < bm.bm_width && 0 <= y && y < bm.bm_height then unsafe_set_point bm x y else () }; value unset_point bm x y = do { if 0 <= x && x < bm.bm_width && 0 <= y && y < bm.bm_height then unsafe_unset_point bm x y else () }; value set_line bm x1 x2 y = do { for x = max x1 0 to min x2 (bm.bm_width - 1) do { unsafe_set_point bm x y } }; value unset_line bm x1 x2 y = do { for x = max x1 0 to min x2 (bm.bm_width - 1) do { unsafe_set_point bm x y } }; value copy_line bm y1 y2 = do { if 0 <= y1 && y1 < bm.bm_height && 0 <= y2 && y2 < bm.bm_height then for x = 0 to bm.bm_width - 1 do { if unsafe_point bm x y1 then unsafe_set_point bm x y2 else unsafe_unset_point bm x y2 } else () }; value print io bm black white end_line = do { iter 0 0 where rec iter x y = do { if y >= bm.bm_height then () else if x >= bm.bm_width then do { IO.write_string io end_line; iter 0 (y+1) } else do { if unsafe_point bm x y then IO.write_string io black else IO.write_string io white; iter (x + 1) y } } };
null
https://raw.githubusercontent.com/5HT/ant/6acf51f4c4ebcc06c52c595776e0293cfa2f1da4/Runtime/Bitmap.ml
ocaml
type bitmap = { bm_width : int; bm_height : int; bm_bytes_per_row : int; bm_data : string }; value make width height = { bm_width = width; bm_height = height; bm_bytes_per_row = (width + 7) / 8; bm_data = String.make (((width + 7) / 8) * height) '\000' }; value get_index bm x y = y * bm.bm_bytes_per_row + x / 8; value get_bit x = (1 lsl (7 - (x land 7))); value unsafe_point bm x y = do { let i = get_index bm x y; Char.code bm.bm_data.[i] land get_bit x <> 0 }; value unsafe_set_point bm x y = do { let i = get_index bm x y; Bytes.set (Bytes.of_string bm.bm_data) i (Char.unsafe_chr (Char.code bm.bm_data.[i] lor get_bit x)) }; value unsafe_unset_point bm x y = do { let i = get_index bm x y; Bytes.set (Bytes.of_string bm.bm_data) i (Char.unsafe_chr (Char.code bm.bm_data.[i] land (lnot (get_bit x)))) }; value point bm x y = do { if 0 <= x && x < bm.bm_width && 0 <= y && y < bm.bm_height then unsafe_point bm x y else False }; value set_point bm x y = do { if 0 <= x && x < bm.bm_width && 0 <= y && y < bm.bm_height then unsafe_set_point bm x y else () }; value unset_point bm x y = do { if 0 <= x && x < bm.bm_width && 0 <= y && y < bm.bm_height then unsafe_unset_point bm x y else () }; value set_line bm x1 x2 y = do { for x = max x1 0 to min x2 (bm.bm_width - 1) do { unsafe_set_point bm x y } }; value unset_line bm x1 x2 y = do { for x = max x1 0 to min x2 (bm.bm_width - 1) do { unsafe_set_point bm x y } }; value copy_line bm y1 y2 = do { if 0 <= y1 && y1 < bm.bm_height && 0 <= y2 && y2 < bm.bm_height then for x = 0 to bm.bm_width - 1 do { if unsafe_point bm x y1 then unsafe_set_point bm x y2 else unsafe_unset_point bm x y2 } else () }; value print io bm black white end_line = do { iter 0 0 where rec iter x y = do { if y >= bm.bm_height then () else if x >= bm.bm_width then do { IO.write_string io end_line; iter 0 (y+1) } else do { if unsafe_point bm x y then IO.write_string io black else IO.write_string io white; iter (x + 1) y } } };
74de9111955cab71b37cf4c2db92fe7c51485cb4fb094e137c57a6eb54876e62
reborg/parallel
core_test.clj
(ns core-test (:import [clojure.lang RT] [java.io File] [java.util.concurrent ConcurrentLinkedQueue]) (:require [parallel.core :as p] [clojure.core.reducers :as r] [clojure.test :refer :all])) (deftest frequencies-test (testing "frequencies with xform" (is (= 5000 (count (p/frequencies (range 1e4) (filter odd?))))) (is (= {":a" 2 ":b" 3} (p/frequencies [:a :a :b :b :b] (map str))))) (testing "a dictionary of words with no dupes" (let [dict (slurp "test/words")] (is (= (count (re-seq #"\S+" dict)) (->> dict (re-seq #"\S+") (frequencies) (map second) (reduce +)))))) (testing "misc examples" (are [expected test-seq] (= (p/frequencies test-seq) expected) {\p 2 \s 4 \i 4 \m 1} "mississippi" {1 4 2 2 3 1} [1 1 1 1 2 2 3] {1 3 2 2 3 1} [1 1 1 2 2 3] {1 4 2 2 3 1} '(1 1 1 1 2 2 3)))) (defn large-map [i] (into {} (map vector (range i) (range i)))) (deftest update-vals-test (testing "sanity" (is (= (map inc (range 1000)) (sort (vals (p/update-vals (large-map 1000) inc))))))) (defmacro repeater [& forms] `(first (distinct (for [i# (range 500)] (do ~@forms))))) (defn chunkedf [f rf size coll] (->> coll (partition-all size) (mapcat f) (reduce rf))) (deftest stateful-transducers (testing "should drop based on chunk size" (is (= (chunkedf #(drop 10 %) + 200 (vec (range 1600))) (repeater (r/fold 200 + (p/xrf + (drop 10)) (p/folder (vec (range 1600))))))) (is (= (chunkedf #(drop 10 %) + 100 (vec (range 204800))) (repeater (r/fold 100 + (p/xrf + (drop 10)) (p/folder (vec (range 204800))))))) (is (= (chunkedf #(drop 10 %) + 400 (vec (range 1600))) (repeater (r/fold + (p/xrf + (drop 10)) (p/folder (vec (range 1600)))))))) (testing "folding by number of chunks" (is (= [3 4 5 6 7 8 9 10 11 12 16 17 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 42 43 44 45 46 47 48 49 50 51] (r/fold "ignored" (r/monoid concat conj) (p/xrf conj (drop 3)) (p/folder (vec (range 52)) 4)))) (is (= (- 1802 (* 3 8)) (count (r/fold "ignored" (r/monoid concat conj) (p/xrf conj (drop 3)) (p/folder (vec (range 1802)) 8)))))) (testing "p/fold entry point at 32 default chunks" (is (= (chunkedf #(drop 10 %) + (/ 2048 32) (vec (map inc (range 2048)))) (p/fold (p/xrf + (drop 10) (map inc)) (vec (range 2048)))))) (testing "p/fold VS r/fold on stateless xducers should be the same" (let [v (vec (range 10000))] (is (= (r/fold + ((comp (map inc) (filter odd?)) +) v) (p/fold (p/xrf + (map inc) (filter odd?)) v) (p/fold + ((comp (map inc) (filter odd?)) +) v))))) (testing "p/transduce" (let [v (vec (range 10000))] (is (= (reduce + 0 (filter odd? (map inc v))) (p/transduce (comp (map inc) (filter odd?)) + v))) (is (= (reduce conj [] (filter odd? (map inc v))) (p/transduce (comp (map inc) (filter odd?)) conj into v))) (is (= [248 249] (nth (p/transduce 4 (comp (drop 240) (partition-all 4)) conj into (vec (range 1000))) 2))))) (testing "p/folding without reducing, just conj" (let [v (vec (range 10000))] (is (= (reduce conj [] (filter odd? (map inc v))) (r/fold (r/monoid into (constantly [])) ((comp (map inc) (filter odd?)) conj) v) (p/fold (r/monoid into (constantly [])) ((comp (map inc) (filter odd?)) conj) v))))) (testing "hashmaps, not just vectors" (is (= {\a [21] \z [23] \h [10 12]} (p/fold (r/monoid #(merge-with into %1 %2) (constantly {})) (fn [m [k v]] (let [c (Character/toLowerCase ^Character (first k))] (assoc m c (conj (get m c []) v)))) (hash-map "abba" 21 "zubb" 23 "hello" 10 "hops" 12))))) (testing "folding hashmaps with transducers" (is (= {0 1 1 2 2 3 3 4} (p/fold (r/monoid merge (constantly {})) (p/xrf conj (map (fn [[k v]] [k (inc v)]))) (hash-map 0 0 1 1 2 2 3 3))))) (testing "exercising all code with larger maps" (is (= 999 ((p/fold (r/monoid merge (constantly {})) (p/xrf conj (filter (fn [[k v]] (even? k))) (map (fn [[k v]] [k (inc v)]))) (zipmap (range 10000) (range 10000))) 998))))) (deftest counting (testing "count a coll" (is (= 100000 (p/count (map inc) (range 1e5)))) (is (= (reduce + (range 50)) (p/count (comp (mapcat range)) (range 50)))))) (deftest grouping (testing "sanity" (is (= 5000 (count ((p/group-by odd? (range 10000)) true))))) (testing "with xducers" (is (= 1667 (count ((p/group-by odd? (range 10000) (map inc) (filter #(zero? (mod % 3)))) true))))) (testing "with stateful xducers" (is (= 1133 (count ((p/group-by odd? (range 10000) (drop 100) (map inc) (filter #(zero? (mod % 3)))) true))))) (testing "anagrams" (let [dict (slurp "test/words")] (is (= #{"caret" "carte" "cater" "crate" "creat" "creta" "react" "recta" "trace"} (into #{} (->> dict (re-seq #"\S+") (p/group-by sort) (sort-by (comp count second) >) (map second) first))))))) (deftest sorting (testing "sanity" (let [coll (reverse (range 1000)) c2 (shuffle (map (comp str char) (range 65 91)))] (is (= (range 1000) (p/sort 200 < coll))) (is (= coll (p/sort 200 > coll))) (is (= (sort compare c2) (p/sort compare c2)))))) ;; (int (/ 100000 (Math/pow 2 8))) (deftest external-sorting (testing "sanity" (let [coll (into [] (reverse (range 1000)))] (is (= 0 (first (p/external-sort 125 compare identity coll)))))) (testing "additional processing" (let [coll (map #(str % "-" %) (range 100000)) fetchf (fn [c] (map #(clojure.string/split % #"-") c))] (is (= ["99999" "99999"] (first (p/external-sort 1562 #(compare (peek %2) (peek %1)) fetchf coll))))))) (deftest min-max (testing "min" (let [c (shuffle (conj (range 100000) -3))] (is (= -3 (p/min c))))) (testing "max" (let [c (shuffle (conj (range 100000) -3))] (is (= 99999 (p/max c))))) (testing "xducers" (let [c (into [] (shuffle (conj (range 100000) -3)))] (is (= 99998 (p/max c (map dec)))))) (testing "min-index" (let [c (conj (range 100000) -3)] (is (= 99999 (p/max c)))))) (deftest pamap-test (testing "sanity" (let [c (to-array (range 100000))] (is (= (map inc (range 10)) (take 10 (p/amap inc c))))))) (deftest distinct-test (let [c (shuffle (apply concat (take 5 (repeat (range 10000)))))] (testing "sanity" (is (= (sort (distinct c)) (sort (p/distinct c))))) (testing "with transducers" (is (= [1 3 5 7 9] (take 5 (sort (p/distinct c (map inc) (filter odd?))))))) (testing "equality semantic" (is (= (sort (distinct (map vector c c))) (sort (p/distinct (map vector c c)))))) (testing "mutability on" (is (= #{1 2 3} (into #{} (binding [p/*mutable* true] (p/distinct [1 2 3])))))))) (deftest reverse-test (testing "swap reverse simmetrical regions in arrays" (let [s (range 10)] (is (= s (let [a (object-array s)] (p/arswap identity 0 9 0 a) (into [] a)))) (is (= (reverse s) (let [a (object-array s)] (p/arswap identity 0 9 5 a) (into [] a)))) (is (= (reverse s) (let [a (object-array s)] (p/arswap identity 0 9 10 a) (into [] a)))) (is (= [9 8 2 3 4 5 6 7 1 0] (let [a (object-array s)] (p/arswap identity 0 9 2 a) (into [] a)))) (is (= [9 8 7 6 5 4 3 2 1] (let [a (object-array (rest s))] (p/arswap identity 0 8 4 a) (into [] a)))) (is (= [9 8 7 4 5 6 3 2 1] (let [a (object-array (rest s))] (p/arswap identity 0 8 3 a) (into [] a)))))) (testing "swap reverse with transform" (let [s (range 10)] (is (= ["9" "8" 2 3 4 5 6 7 "1" "0"] (let [a (object-array s)] (p/arswap str 0 9 2 a) (into [] a)))) (is (= [:9 :8 :7 4 5 6 :3 :2 :1] (let [a (object-array (rest s))] (p/arswap (comp keyword str) 0 8 3 a) (into [] a)))))) (testing "sanity" (is (= nil (p/armap identity nil))) (is (= (reverse ()) (let [a (object-array ())] (p/armap identity a) (into [] a)))) (is (= (reverse (range 1)) (let [a (object-array (range 1))] (p/armap identity a) (into [] a)))) (is (= (reverse (range 5)) (let [a (object-array (range 5))] (p/armap identity a) (into [] a)))) (is (= (reverse (range 1e2)) (let [a (object-array (range 1e2))] (p/armap identity a) (into [] a)))) (let [xs (shuffle (range 11)) a (object-array xs)] (is (= (reverse (map str xs)) (do (p/armap str a) (into [] a))))))) (deftest slurping (testing "slurping sanity" (is (= (slurp "test/words") (p/slurp (File. "test/words")))))) (deftest parallel-let (testing "it works like normal let" (is (= 3 (p/let [a 1 b 2] (+ a b)))) (is (= 3 (p/let [a (future 1) b (future 2)] (+ @a @b)))) (is (= 6 (p/let [[a b] [1 2] {c :c} {:c 3}] (+ a b c)))) (is (= 300 (p/let [a (do (Thread/sleep 20) 100) b (do (Thread/sleep 10) 200)] (+ a b)))))) (deftest parallel-args (testing "works like a standard function invocation" (is (= 6 (p/args + 1 2 3))) (is (= 1 (p/args first [1 2 3]))) (is (= 300 (p/args + (do (Thread/sleep 20) 100) (do (Thread/sleep 10) 200)))))) (deftest parallel-and (testing "works like a standard and" (is (= (and) (p/and))) (is (= "a" (p/and true 1 "a"))) (is (= :x (p/and :y true :x))) (is (= false (p/and true false true))) (is (p/and (do (Thread/sleep 20) true) (do (Thread/sleep 10) true))))) (deftest parallel-or (testing "works like a standard or" (is (= (or) (p/or))) (is (= true (p/or true 1 "a"))) (is (= :y (p/or false :y true :x))) (is (= true (p/or true false true))) (is (p/or (do (Thread/sleep 20) false) (do (Thread/sleep 10) true))))) (deftest parallel-do-doto (testing "like do, but forms evaluate in parallel." (is (= nil (p/do))) (is (= 1 (p/do 1))) (is (some #{[1 2] [2 1]} (set (repeatedly 50 #(let [a (ConcurrentLinkedQueue.)] (p/do (.add a 1) (.add a 2)) (vec a))))))) (testing "like doto, but forms evaluated in parallel." (is (= 1 (p/doto 1))) (is (= [1 2] (vec (p/doto (ConcurrentLinkedQueue.) (.add 1) (.add 2))))))) (deftest pmap-test (testing "like pmap but results are not ordered" (is (= (set (range 1 1001)) (set (p/pmap inc (range 1000)))))))
null
https://raw.githubusercontent.com/reborg/parallel/7fde6e48e49455f213c435239c35d31c60e08948/test/core_test.clj
clojure
(int (/ 100000 (Math/pow 2 8)))
(ns core-test (:import [clojure.lang RT] [java.io File] [java.util.concurrent ConcurrentLinkedQueue]) (:require [parallel.core :as p] [clojure.core.reducers :as r] [clojure.test :refer :all])) (deftest frequencies-test (testing "frequencies with xform" (is (= 5000 (count (p/frequencies (range 1e4) (filter odd?))))) (is (= {":a" 2 ":b" 3} (p/frequencies [:a :a :b :b :b] (map str))))) (testing "a dictionary of words with no dupes" (let [dict (slurp "test/words")] (is (= (count (re-seq #"\S+" dict)) (->> dict (re-seq #"\S+") (frequencies) (map second) (reduce +)))))) (testing "misc examples" (are [expected test-seq] (= (p/frequencies test-seq) expected) {\p 2 \s 4 \i 4 \m 1} "mississippi" {1 4 2 2 3 1} [1 1 1 1 2 2 3] {1 3 2 2 3 1} [1 1 1 2 2 3] {1 4 2 2 3 1} '(1 1 1 1 2 2 3)))) (defn large-map [i] (into {} (map vector (range i) (range i)))) (deftest update-vals-test (testing "sanity" (is (= (map inc (range 1000)) (sort (vals (p/update-vals (large-map 1000) inc))))))) (defmacro repeater [& forms] `(first (distinct (for [i# (range 500)] (do ~@forms))))) (defn chunkedf [f rf size coll] (->> coll (partition-all size) (mapcat f) (reduce rf))) (deftest stateful-transducers (testing "should drop based on chunk size" (is (= (chunkedf #(drop 10 %) + 200 (vec (range 1600))) (repeater (r/fold 200 + (p/xrf + (drop 10)) (p/folder (vec (range 1600))))))) (is (= (chunkedf #(drop 10 %) + 100 (vec (range 204800))) (repeater (r/fold 100 + (p/xrf + (drop 10)) (p/folder (vec (range 204800))))))) (is (= (chunkedf #(drop 10 %) + 400 (vec (range 1600))) (repeater (r/fold + (p/xrf + (drop 10)) (p/folder (vec (range 1600)))))))) (testing "folding by number of chunks" (is (= [3 4 5 6 7 8 9 10 11 12 16 17 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 42 43 44 45 46 47 48 49 50 51] (r/fold "ignored" (r/monoid concat conj) (p/xrf conj (drop 3)) (p/folder (vec (range 52)) 4)))) (is (= (- 1802 (* 3 8)) (count (r/fold "ignored" (r/monoid concat conj) (p/xrf conj (drop 3)) (p/folder (vec (range 1802)) 8)))))) (testing "p/fold entry point at 32 default chunks" (is (= (chunkedf #(drop 10 %) + (/ 2048 32) (vec (map inc (range 2048)))) (p/fold (p/xrf + (drop 10) (map inc)) (vec (range 2048)))))) (testing "p/fold VS r/fold on stateless xducers should be the same" (let [v (vec (range 10000))] (is (= (r/fold + ((comp (map inc) (filter odd?)) +) v) (p/fold (p/xrf + (map inc) (filter odd?)) v) (p/fold + ((comp (map inc) (filter odd?)) +) v))))) (testing "p/transduce" (let [v (vec (range 10000))] (is (= (reduce + 0 (filter odd? (map inc v))) (p/transduce (comp (map inc) (filter odd?)) + v))) (is (= (reduce conj [] (filter odd? (map inc v))) (p/transduce (comp (map inc) (filter odd?)) conj into v))) (is (= [248 249] (nth (p/transduce 4 (comp (drop 240) (partition-all 4)) conj into (vec (range 1000))) 2))))) (testing "p/folding without reducing, just conj" (let [v (vec (range 10000))] (is (= (reduce conj [] (filter odd? (map inc v))) (r/fold (r/monoid into (constantly [])) ((comp (map inc) (filter odd?)) conj) v) (p/fold (r/monoid into (constantly [])) ((comp (map inc) (filter odd?)) conj) v))))) (testing "hashmaps, not just vectors" (is (= {\a [21] \z [23] \h [10 12]} (p/fold (r/monoid #(merge-with into %1 %2) (constantly {})) (fn [m [k v]] (let [c (Character/toLowerCase ^Character (first k))] (assoc m c (conj (get m c []) v)))) (hash-map "abba" 21 "zubb" 23 "hello" 10 "hops" 12))))) (testing "folding hashmaps with transducers" (is (= {0 1 1 2 2 3 3 4} (p/fold (r/monoid merge (constantly {})) (p/xrf conj (map (fn [[k v]] [k (inc v)]))) (hash-map 0 0 1 1 2 2 3 3))))) (testing "exercising all code with larger maps" (is (= 999 ((p/fold (r/monoid merge (constantly {})) (p/xrf conj (filter (fn [[k v]] (even? k))) (map (fn [[k v]] [k (inc v)]))) (zipmap (range 10000) (range 10000))) 998))))) (deftest counting (testing "count a coll" (is (= 100000 (p/count (map inc) (range 1e5)))) (is (= (reduce + (range 50)) (p/count (comp (mapcat range)) (range 50)))))) (deftest grouping (testing "sanity" (is (= 5000 (count ((p/group-by odd? (range 10000)) true))))) (testing "with xducers" (is (= 1667 (count ((p/group-by odd? (range 10000) (map inc) (filter #(zero? (mod % 3)))) true))))) (testing "with stateful xducers" (is (= 1133 (count ((p/group-by odd? (range 10000) (drop 100) (map inc) (filter #(zero? (mod % 3)))) true))))) (testing "anagrams" (let [dict (slurp "test/words")] (is (= #{"caret" "carte" "cater" "crate" "creat" "creta" "react" "recta" "trace"} (into #{} (->> dict (re-seq #"\S+") (p/group-by sort) (sort-by (comp count second) >) (map second) first))))))) (deftest sorting (testing "sanity" (let [coll (reverse (range 1000)) c2 (shuffle (map (comp str char) (range 65 91)))] (is (= (range 1000) (p/sort 200 < coll))) (is (= coll (p/sort 200 > coll))) (is (= (sort compare c2) (p/sort compare c2)))))) (deftest external-sorting (testing "sanity" (let [coll (into [] (reverse (range 1000)))] (is (= 0 (first (p/external-sort 125 compare identity coll)))))) (testing "additional processing" (let [coll (map #(str % "-" %) (range 100000)) fetchf (fn [c] (map #(clojure.string/split % #"-") c))] (is (= ["99999" "99999"] (first (p/external-sort 1562 #(compare (peek %2) (peek %1)) fetchf coll))))))) (deftest min-max (testing "min" (let [c (shuffle (conj (range 100000) -3))] (is (= -3 (p/min c))))) (testing "max" (let [c (shuffle (conj (range 100000) -3))] (is (= 99999 (p/max c))))) (testing "xducers" (let [c (into [] (shuffle (conj (range 100000) -3)))] (is (= 99998 (p/max c (map dec)))))) (testing "min-index" (let [c (conj (range 100000) -3)] (is (= 99999 (p/max c)))))) (deftest pamap-test (testing "sanity" (let [c (to-array (range 100000))] (is (= (map inc (range 10)) (take 10 (p/amap inc c))))))) (deftest distinct-test (let [c (shuffle (apply concat (take 5 (repeat (range 10000)))))] (testing "sanity" (is (= (sort (distinct c)) (sort (p/distinct c))))) (testing "with transducers" (is (= [1 3 5 7 9] (take 5 (sort (p/distinct c (map inc) (filter odd?))))))) (testing "equality semantic" (is (= (sort (distinct (map vector c c))) (sort (p/distinct (map vector c c)))))) (testing "mutability on" (is (= #{1 2 3} (into #{} (binding [p/*mutable* true] (p/distinct [1 2 3])))))))) (deftest reverse-test (testing "swap reverse simmetrical regions in arrays" (let [s (range 10)] (is (= s (let [a (object-array s)] (p/arswap identity 0 9 0 a) (into [] a)))) (is (= (reverse s) (let [a (object-array s)] (p/arswap identity 0 9 5 a) (into [] a)))) (is (= (reverse s) (let [a (object-array s)] (p/arswap identity 0 9 10 a) (into [] a)))) (is (= [9 8 2 3 4 5 6 7 1 0] (let [a (object-array s)] (p/arswap identity 0 9 2 a) (into [] a)))) (is (= [9 8 7 6 5 4 3 2 1] (let [a (object-array (rest s))] (p/arswap identity 0 8 4 a) (into [] a)))) (is (= [9 8 7 4 5 6 3 2 1] (let [a (object-array (rest s))] (p/arswap identity 0 8 3 a) (into [] a)))))) (testing "swap reverse with transform" (let [s (range 10)] (is (= ["9" "8" 2 3 4 5 6 7 "1" "0"] (let [a (object-array s)] (p/arswap str 0 9 2 a) (into [] a)))) (is (= [:9 :8 :7 4 5 6 :3 :2 :1] (let [a (object-array (rest s))] (p/arswap (comp keyword str) 0 8 3 a) (into [] a)))))) (testing "sanity" (is (= nil (p/armap identity nil))) (is (= (reverse ()) (let [a (object-array ())] (p/armap identity a) (into [] a)))) (is (= (reverse (range 1)) (let [a (object-array (range 1))] (p/armap identity a) (into [] a)))) (is (= (reverse (range 5)) (let [a (object-array (range 5))] (p/armap identity a) (into [] a)))) (is (= (reverse (range 1e2)) (let [a (object-array (range 1e2))] (p/armap identity a) (into [] a)))) (let [xs (shuffle (range 11)) a (object-array xs)] (is (= (reverse (map str xs)) (do (p/armap str a) (into [] a))))))) (deftest slurping (testing "slurping sanity" (is (= (slurp "test/words") (p/slurp (File. "test/words")))))) (deftest parallel-let (testing "it works like normal let" (is (= 3 (p/let [a 1 b 2] (+ a b)))) (is (= 3 (p/let [a (future 1) b (future 2)] (+ @a @b)))) (is (= 6 (p/let [[a b] [1 2] {c :c} {:c 3}] (+ a b c)))) (is (= 300 (p/let [a (do (Thread/sleep 20) 100) b (do (Thread/sleep 10) 200)] (+ a b)))))) (deftest parallel-args (testing "works like a standard function invocation" (is (= 6 (p/args + 1 2 3))) (is (= 1 (p/args first [1 2 3]))) (is (= 300 (p/args + (do (Thread/sleep 20) 100) (do (Thread/sleep 10) 200)))))) (deftest parallel-and (testing "works like a standard and" (is (= (and) (p/and))) (is (= "a" (p/and true 1 "a"))) (is (= :x (p/and :y true :x))) (is (= false (p/and true false true))) (is (p/and (do (Thread/sleep 20) true) (do (Thread/sleep 10) true))))) (deftest parallel-or (testing "works like a standard or" (is (= (or) (p/or))) (is (= true (p/or true 1 "a"))) (is (= :y (p/or false :y true :x))) (is (= true (p/or true false true))) (is (p/or (do (Thread/sleep 20) false) (do (Thread/sleep 10) true))))) (deftest parallel-do-doto (testing "like do, but forms evaluate in parallel." (is (= nil (p/do))) (is (= 1 (p/do 1))) (is (some #{[1 2] [2 1]} (set (repeatedly 50 #(let [a (ConcurrentLinkedQueue.)] (p/do (.add a 1) (.add a 2)) (vec a))))))) (testing "like doto, but forms evaluated in parallel." (is (= 1 (p/doto 1))) (is (= [1 2] (vec (p/doto (ConcurrentLinkedQueue.) (.add 1) (.add 2))))))) (deftest pmap-test (testing "like pmap but results are not ordered" (is (= (set (range 1 1001)) (set (p/pmap inc (range 1000)))))))
7b7878e5f27719d6c7c088156cefa68532096872817033daffa9d1ee7faae5c7
ChrisPenner/lens-regex-pcre
Spec.hs
import Test.Hspec import Text import ByteString main :: IO () main = hspec $ do describe "text" Text.spec describe "bytestring" ByteString.spec
null
https://raw.githubusercontent.com/ChrisPenner/lens-regex-pcre/c7587b825f8ab788720d88cbafab72cc72690802/test/Spec.hs
haskell
import Test.Hspec import Text import ByteString main :: IO () main = hspec $ do describe "text" Text.spec describe "bytestring" ByteString.spec
18143ce605ce1d24ff1df50ce71e88a895d0485a9178a957fed269fb1dd42caa
mhkoji/Senn
lib.lisp
(defpackage :senn.t.win.lib (:use :cl) (:export :make-ime)) (in-package :senn.t.win.lib) (defmacro make-ime (&key test) `(progn (senn.lib.win:init (merge-pathnames "t/kkc-engine-today.py" (asdf:system-source-directory :senn))) (unwind-protect (let* ((ime (senn.lib.win:make-ime)) (state (senn.im.converting:convert ime "きょうは"))) (,test (equal (senn.t.im-util:converting-state-segment-strings state) '("今日/きょう" "は/は")))) (senn.lib.win:destroy)))) (senn.t.win:add-tests :lib make-ime)
null
https://raw.githubusercontent.com/mhkoji/Senn/30f930e14a80796621ca4faa8ca3b1794f8a4d9f/senn/t/win/lib.lisp
lisp
(defpackage :senn.t.win.lib (:use :cl) (:export :make-ime)) (in-package :senn.t.win.lib) (defmacro make-ime (&key test) `(progn (senn.lib.win:init (merge-pathnames "t/kkc-engine-today.py" (asdf:system-source-directory :senn))) (unwind-protect (let* ((ime (senn.lib.win:make-ime)) (state (senn.im.converting:convert ime "きょうは"))) (,test (equal (senn.t.im-util:converting-state-segment-strings state) '("今日/きょう" "は/は")))) (senn.lib.win:destroy)))) (senn.t.win:add-tests :lib make-ime)
439466afc7a825d2ffa92e018825ff02a466a1173aa0c6e1c854384cc103e078
cedlemo/OCaml-GI-ctypes-bindings-generator
Target_entry.ml
open Ctypes open Foreign type t let t_typ : t structure typ = structure "Target_entry" let f_target = field t_typ "target" (string) let f_flags = field t_typ "flags" (uint32_t) let f_info = field t_typ "info" (uint32_t) let _ = seal t_typ let create = foreign "gtk_target_entry_new" (string @-> uint32_t @-> uint32_t @-> returning (ptr t_typ)) let copy = foreign "gtk_target_entry_copy" (ptr t_typ @-> returning (ptr t_typ)) let free = foreign "gtk_target_entry_free" (ptr t_typ @-> returning (void))
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Target_entry.ml
ocaml
open Ctypes open Foreign type t let t_typ : t structure typ = structure "Target_entry" let f_target = field t_typ "target" (string) let f_flags = field t_typ "flags" (uint32_t) let f_info = field t_typ "info" (uint32_t) let _ = seal t_typ let create = foreign "gtk_target_entry_new" (string @-> uint32_t @-> uint32_t @-> returning (ptr t_typ)) let copy = foreign "gtk_target_entry_copy" (ptr t_typ @-> returning (ptr t_typ)) let free = foreign "gtk_target_entry_free" (ptr t_typ @-> returning (void))
0bd7b3a5ec9c65bf13e3d983ece1f3b04061bf9b47ed5ffc6532b69e262a6ecc
Javran/advent-of-code
Day25.hs
module Javran.AdventOfCode.Y2018.Day25 ( ) where import Control.Monad import Control.Monad.ST import qualified Data.Vector as V import Javran.AdventOfCode.Prelude import qualified Javran.AdventOfCode.UnionFind.ST as UF import Text.ParserCombinators.ReadP hiding (count, get, many) data Day25 deriving (Generic) type Pt = (Int, Int, Int, Int) ptP :: ReadP Pt ptP = do [a, b, c, d] <- intP `sepBy1` char ',' pure (a, b, c, d) where intP = readS_to_P (reads @Int) countConstellations :: [Pt] -> ST s Int countConstellations xs = do let pts = V.fromList xs ss <- V.fromListN (V.length pts) <$> mapM UF.fresh xs forM_ ( do (i, xs0) <- pickInOrder [0 .. V.length pts - 1] j <- xs0 pure (i, j) ) $ \(i, j) -> do when (manhattan (pts V.! i) (pts V.! j) <= 3) do UF.union (ss V.! i) (ss V.! j) UF.countClusters ss instance Solution Day25 where solutionRun _ SolutionContext {getInputS, answerShow} = do xs <- fmap (consumeOrDie ptP) . lines <$> getInputS answerShow $ runST $ countConstellations xs
null
https://raw.githubusercontent.com/Javran/advent-of-code/676ef13c2f9d341cf7de0f383335a1cf577bd73d/src/Javran/AdventOfCode/Y2018/Day25.hs
haskell
module Javran.AdventOfCode.Y2018.Day25 ( ) where import Control.Monad import Control.Monad.ST import qualified Data.Vector as V import Javran.AdventOfCode.Prelude import qualified Javran.AdventOfCode.UnionFind.ST as UF import Text.ParserCombinators.ReadP hiding (count, get, many) data Day25 deriving (Generic) type Pt = (Int, Int, Int, Int) ptP :: ReadP Pt ptP = do [a, b, c, d] <- intP `sepBy1` char ',' pure (a, b, c, d) where intP = readS_to_P (reads @Int) countConstellations :: [Pt] -> ST s Int countConstellations xs = do let pts = V.fromList xs ss <- V.fromListN (V.length pts) <$> mapM UF.fresh xs forM_ ( do (i, xs0) <- pickInOrder [0 .. V.length pts - 1] j <- xs0 pure (i, j) ) $ \(i, j) -> do when (manhattan (pts V.! i) (pts V.! j) <= 3) do UF.union (ss V.! i) (ss V.! j) UF.countClusters ss instance Solution Day25 where solutionRun _ SolutionContext {getInputS, answerShow} = do xs <- fmap (consumeOrDie ptP) . lines <$> getInputS answerShow $ runST $ countConstellations xs
6b6cbcd1279689698b14e4711e4188a7a2bd1b7585a7f4c28a691bba1e0f6250
status-im/extensions-fiddle
ethereum.cljs
(ns react-native-web.ethereum (:require [re-frame.core :as re-frame] [status-im.abi-spec :as abi-spec])) (defn rpc-args [method params from] {:method method :params params :from from}) (defn parse-call-result [o outputs] (let [result (get (js->clj o) "result")] (cond (= "0x" result) nil (and outputs result) (abi-spec/decode result outputs) :else result))) (defn rpc-dispatch [error result f on-success on-failure] (when (and result on-success f) (on-success {:value (f result)})) (when (and error on-failure) (on-failure {:value error}))) (defn- execute-ethcall [{:keys [to method params outputs on-success on-failure]} ethereum-addr] (let [tx-object {:to to :data (when method (abi-spec/encode method params))}] {:extensions/send-async [(rpc-args "eth_call" [tx-object "latest"] ethereum-addr) #(rpc-dispatch %1 %2 (fn [o] (parse-call-result o outputs)) on-success on-failure)]})) (defn- execute-send-transaction [{:keys [method params on-success on-failure] :as arguments} ethereum-addr] (let [tx-object (assoc (select-keys arguments [:to :gas :gas-price :value :nonce]) :from ethereum-addr :data (when (and method params) (abi-spec/encode method params)))] {:extensions/send-async [(rpc-args "eth_sendTransaction" [tx-object] ethereum-addr) #(rpc-dispatch %1 %2 (fn [o] (parse-call-result o nil)) on-success on-failure)]})) (re-frame.core/reg-fx :extensions/send-async (fn [[obj callback]] (.sendAsync js/ethereum (clj->js obj) callback))) (re-frame/reg-event-fx :extensions/ethereum-call (fn [{{:keys [ethereum-addr]} :db} [_ _ arguments]] (when ethereum-addr (execute-ethcall arguments ethereum-addr)))) (re-frame/reg-event-fx :extensions/ethereum-send-transaction (fn [{{:keys [ethereum-addr]} :db} [_ _ arguments]] (when ethereum-addr (execute-send-transaction arguments ethereum-addr)))) (re-frame.core/reg-fx :extensions/init-wallet-fx (fn [] (when (exists? js/ethereum) (-> (.enable js/ethereum) (.then #(re-frame/dispatch [:set :ethereum-addr (first (js->clj %))])) (.catch #()))))) (re-frame/reg-event-fx :extensions/init-wallet (fn [_ _] {:extensions/init-wallet-fx nil}))
null
https://raw.githubusercontent.com/status-im/extensions-fiddle/3f3544e90ff0ecdb1dfd051886b5a5f28e506b0b/src/react_native_web/ethereum.cljs
clojure
(ns react-native-web.ethereum (:require [re-frame.core :as re-frame] [status-im.abi-spec :as abi-spec])) (defn rpc-args [method params from] {:method method :params params :from from}) (defn parse-call-result [o outputs] (let [result (get (js->clj o) "result")] (cond (= "0x" result) nil (and outputs result) (abi-spec/decode result outputs) :else result))) (defn rpc-dispatch [error result f on-success on-failure] (when (and result on-success f) (on-success {:value (f result)})) (when (and error on-failure) (on-failure {:value error}))) (defn- execute-ethcall [{:keys [to method params outputs on-success on-failure]} ethereum-addr] (let [tx-object {:to to :data (when method (abi-spec/encode method params))}] {:extensions/send-async [(rpc-args "eth_call" [tx-object "latest"] ethereum-addr) #(rpc-dispatch %1 %2 (fn [o] (parse-call-result o outputs)) on-success on-failure)]})) (defn- execute-send-transaction [{:keys [method params on-success on-failure] :as arguments} ethereum-addr] (let [tx-object (assoc (select-keys arguments [:to :gas :gas-price :value :nonce]) :from ethereum-addr :data (when (and method params) (abi-spec/encode method params)))] {:extensions/send-async [(rpc-args "eth_sendTransaction" [tx-object] ethereum-addr) #(rpc-dispatch %1 %2 (fn [o] (parse-call-result o nil)) on-success on-failure)]})) (re-frame.core/reg-fx :extensions/send-async (fn [[obj callback]] (.sendAsync js/ethereum (clj->js obj) callback))) (re-frame/reg-event-fx :extensions/ethereum-call (fn [{{:keys [ethereum-addr]} :db} [_ _ arguments]] (when ethereum-addr (execute-ethcall arguments ethereum-addr)))) (re-frame/reg-event-fx :extensions/ethereum-send-transaction (fn [{{:keys [ethereum-addr]} :db} [_ _ arguments]] (when ethereum-addr (execute-send-transaction arguments ethereum-addr)))) (re-frame.core/reg-fx :extensions/init-wallet-fx (fn [] (when (exists? js/ethereum) (-> (.enable js/ethereum) (.then #(re-frame/dispatch [:set :ethereum-addr (first (js->clj %))])) (.catch #()))))) (re-frame/reg-event-fx :extensions/init-wallet (fn [_ _] {:extensions/init-wallet-fx nil}))
73fae42e17d71953700f835cba319f454f778d22fe4ba0fd912e312c6748cf03
karlhof26/gimp-scheme
make-rotationally-seamless.scm
; make-rotationally-seamless.scm ; version 1.1 ; This is Script - Fu program written for GIMP 2.8 . ; ; Updated for Gimp-2.10.20 ; ; Its purpose is to help create texture images that can not only be tiled ; through translation, but also when combined with flipping and rotation. It works by taking one half of one side and flipping and rotating it around the ; other edges. It leaves the original image as a layer underneath so you can ; fine tune the blending. ; ; Blend width (0 for full): ; Sets the blend width around the edge of the image. If this is '0', it does ; not attempt to blend, instead it leaves the newly created layer for you to ; mask the middle and reveal the original image. ; ; Preview X tiles: ; Preview Y tiles: ; If either (or both) of these are greater than '1', it will create a preview ; tiled image where the tiles are rotated and flipped randomly. It will also ; create an additional undo point to easily go back to the untiled version ; without re-running the script. ; ; It works best on images that are mostly uniform and square, and although it ; will resize the image to make it square if necessary, it is not recommended. ; This also leaves pretty obvious mirroring when tiled, so unless you blend it ; manually, the results are usually less than spectacular. ; ; Copyright 2015 ; 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. ; (define (script-fu-make-rotationally-seamless image layerBase sideStart blend tilesX tilesY) (let* ( (layerBasePosition (car (gimp-image-get-item-position image layerBase))) (width (car (gimp-drawable-width layerBase))) (height (car (gimp-drawable-height layerBase))) (layerComplete (car (gimp-layer-new-from-drawable layerBase image))) (layerFloating 0) (size 0) (sel 0) (trans 0) (rotate 0) (flip 0) (temp 0) ) (set! blend (round blend)) : ;0 Top left 1 Top right 2 Bottom left 3 Bottom right ;4 Left top 5 Left bottom ;6 Right top ;7 Right bottom (if (or (= sideStart 0) (= sideStart 1)) (set! rotate 0) ) (if (or (= sideStart 2) (= sideStart 3)) (set! rotate 2) ) (if (or (= sideStart 4) (= sideStart 5)) (set! rotate 1) ) (if (or (= sideStart 6) (= sideStart 7)) (set! rotate 3) ) (if (or (= sideStart 1) (= sideStart 2) (= sideStart 4) (= sideStart 7)) (set! flip #t) ; True (set! flip #f) ; False ) (gimp-context-push) (gimp-context-set-defaults) (gimp-image-undo-group-start image) (gimp-image-insert-layer image layerComplete 0 layerBasePosition) (gimp-layer-add-alpha layerComplete) (gimp-item-set-name layerComplete "layerComplete") ; Pre rotate and flip image (if (= rotate 1) (gimp-image-rotate image ROTATE-90) ) (if (= rotate 2) (gimp-image-rotate image ROTATE-180) ) (if (= rotate 3) (gimp-image-rotate image ROTATE-270) ) (if flip (gimp-image-flip image ORIENTATION-HORIZONTAL) ) ; Resize image to square (if (= width height) (set! size width) (begin (if (< width height) (begin (gimp-image-resize image height height 0 0) (gimp-layer-resize layerBase height height 0 0) (gimp-layer-resize layerComplete height height 0 0) (set! size height) ) (begin (gimp-image-resize image width width 0 0) (gimp-layer-resize layerBase width width 0 0) (gimp-layer-resize layerComplete width width 0 0) (set! size width) ) ) ) ) (if (= 0 (modulo size 2)) (begin ;even (set! sel (+ 1 (/ size 2))) (set! trans (/ size 2)) ) (begin ;odd (set! sel (ceiling (/ size 2))) (set! trans (ceiling (/ size 2))) ) ) (gimp-context-set-antialias FALSE) (gimp-context-set-feather FALSE) ;top right (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) insert by karlhof26 ;(gimp-image-insert-layer image layerFloating 0 -1) (gimp-item-transform-flip-simple layerFloating ORIENTATION-HORIZONTAL TRUE 0) (gimp-layer-translate layerFloating trans 0) ;right top (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) insert by karlhof26 ;(gimp-image-insert-layer image layerFloating 0 -1) (gimp-displays-flush) (gimp-item-transform-rotate-simple layerFloating ROTATE-90 TRUE 0 0) (gimp-layer-translate layerFloating trans 0) ;right bottom (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) (gimp-item-transform-flip-simple layerFloating ORIENTATION-HORIZONTAL TRUE 0) (gimp-item-transform-rotate-simple layerFloating ROTATE-90 TRUE 0 0) (gimp-layer-translate layerFloating trans trans) (gimp-displays-flush) ;bottom right (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) (gimp-item-transform-rotate-simple layerFloating ROTATE-180 TRUE 0 0) (gimp-layer-translate layerFloating trans trans) (gimp-displays-flush) ;bottom left (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) (gimp-item-transform-flip-simple layerFloating ORIENTATION-HORIZONTAL TRUE 0) (gimp-item-transform-rotate-simple layerFloating ROTATE-180 TRUE 0 0) (gimp-layer-translate layerFloating 0 trans) (gimp-displays-flush) ;left bottom (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) (gimp-item-transform-rotate-simple layerFloating ROTATE-270 TRUE 0 0) (gimp-layer-translate layerFloating 0 trans) ;left top (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) (gimp-item-transform-flip-simple layerFloating ORIENTATION-HORIZONTAL TRUE 0) (gimp-item-transform-rotate-simple layerFloating ROTATE-270 TRUE 0 0) (gimp-floating-sel-anchor layerFloating) (gimp-displays-flush) ; Rotate and flip image back (if flip (gimp-image-flip image ORIENTATION-HORIZONTAL) ) (if (= rotate 1) (gimp-image-rotate image ROTATE-270) ) (if (= rotate 2) (gimp-image-rotate image ROTATE-180) ) (if (= rotate 3) (gimp-image-rotate image ROTATE-90) ) (gimp-displays-flush) (if (> blend 0) (begin ;(gimp-message "blend not eq to 0") (gimp-selection-all image) (gimp-selection-shrink image (ceiling (/ blend 2))) (gimp-selection-feather image blend) rows added by karlhof26 (gimp-selection-invert image) (gimp-edit-clear layerComplete) (gimp-selection-none image) ) ) (gimp-displays-flush) ;(quit) (if (or (not (= tilesX 1)) (not (= tilesY 1))) (begin ;(gimp-message "do tile random rotation") (gimp-image-undo-group-end image) (gimp-image-undo-group-start image) (set! layerBase (car (gimp-image-merge-down image layerComplete CLIP-TO-IMAGE))) (script-fu-tile-random-rotation image layerBase tilesX tilesY TRUE TRUE) ) ) (gimp-image-undo-group-end image) (gimp-displays-flush) (gimp-context-pop) ) ) (script-fu-register "script-fu-make-rotationally-seamless" "Make _rotationally seamless..." "Copy, rotate, and flip half of one edge of the image around its border. \nfile:make-rotationally-seamless.scm" "John Tasto <>" "John Tasto" "2015/03/03" "RGB* GRAY* INDEXED*" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0 SF-OPTION _"Side to duplicate" '("Top left" "Top right" "Bottom left" "Bottom right" "Left top" "Left bottom" "Right top" "Right bottom") SF-ADJUSTMENT "Blend width (0 for full)" '(0 0 1024 1 8 0 SF-SPINNER) SF-ADJUSTMENT "Preview X tiles" '(1 1 256 1 1 0 SF-SPINNER) SF-ADJUSTMENT "Preview Y tiles" '(1 1 256 1 1 0 SF-SPINNER) ) (script-fu-menu-register "script-fu-make-rotationally-seamless" "<Image>/Script-Fu2/Pattern") ;end of script
null
https://raw.githubusercontent.com/karlhof26/gimp-scheme/a8de87a29db39337929b22eb4f81345f91765f55/make-rotationally-seamless.scm
scheme
make-rotationally-seamless.scm version 1.1 Updated for Gimp-2.10.20 Its purpose is to help create texture images that can not only be tiled through translation, but also when combined with flipping and rotation. It other edges. It leaves the original image as a layer underneath so you can fine tune the blending. Blend width (0 for full): Sets the blend width around the edge of the image. If this is '0', it does not attempt to blend, instead it leaves the newly created layer for you to mask the middle and reveal the original image. Preview X tiles: Preview Y tiles: If either (or both) of these are greater than '1', it will create a preview tiled image where the tiles are rotated and flipped randomly. It will also create an additional undo point to easily go back to the untiled version without re-running the script. It works best on images that are mostly uniform and square, and although it will resize the image to make it square if necessary, it is not recommended. This also leaves pretty obvious mirroring when tiled, so unless you blend it manually, the results are usually less than spectacular. 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. 0 Top left 4 Left top 6 Right top 7 Right bottom True False Pre rotate and flip image Resize image to square even odd top right (gimp-image-insert-layer image layerFloating 0 -1) right top (gimp-image-insert-layer image layerFloating 0 -1) right bottom bottom right bottom left left bottom left top Rotate and flip image back (gimp-message "blend not eq to 0") (quit) (gimp-message "do tile random rotation") end of script
This is Script - Fu program written for GIMP 2.8 . works by taking one half of one side and flipping and rotating it around the Copyright 2015 you may not use this file except in compliance with the License . distributed under the License is distributed on an " AS IS " BASIS , (define (script-fu-make-rotationally-seamless image layerBase sideStart blend tilesX tilesY) (let* ( (layerBasePosition (car (gimp-image-get-item-position image layerBase))) (width (car (gimp-drawable-width layerBase))) (height (car (gimp-drawable-height layerBase))) (layerComplete (car (gimp-layer-new-from-drawable layerBase image))) (layerFloating 0) (size 0) (sel 0) (trans 0) (rotate 0) (flip 0) (temp 0) ) (set! blend (round blend)) : 1 Top right 2 Bottom left 3 Bottom right 5 Left bottom (if (or (= sideStart 0) (= sideStart 1)) (set! rotate 0) ) (if (or (= sideStart 2) (= sideStart 3)) (set! rotate 2) ) (if (or (= sideStart 4) (= sideStart 5)) (set! rotate 1) ) (if (or (= sideStart 6) (= sideStart 7)) (set! rotate 3) ) (if (or (= sideStart 1) (= sideStart 2) (= sideStart 4) (= sideStart 7)) ) (gimp-context-push) (gimp-context-set-defaults) (gimp-image-undo-group-start image) (gimp-image-insert-layer image layerComplete 0 layerBasePosition) (gimp-layer-add-alpha layerComplete) (gimp-item-set-name layerComplete "layerComplete") (if (= rotate 1) (gimp-image-rotate image ROTATE-90) ) (if (= rotate 2) (gimp-image-rotate image ROTATE-180) ) (if (= rotate 3) (gimp-image-rotate image ROTATE-270) ) (if flip (gimp-image-flip image ORIENTATION-HORIZONTAL) ) (if (= width height) (set! size width) (begin (if (< width height) (begin (gimp-image-resize image height height 0 0) (gimp-layer-resize layerBase height height 0 0) (gimp-layer-resize layerComplete height height 0 0) (set! size height) ) (begin (gimp-image-resize image width width 0 0) (gimp-layer-resize layerBase width width 0 0) (gimp-layer-resize layerComplete width width 0 0) (set! size width) ) ) ) ) (if (= 0 (modulo size 2)) (set! sel (+ 1 (/ size 2))) (set! trans (/ size 2)) ) (set! sel (ceiling (/ size 2))) (set! trans (ceiling (/ size 2))) ) ) (gimp-context-set-antialias FALSE) (gimp-context-set-feather FALSE) (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) insert by karlhof26 (gimp-item-transform-flip-simple layerFloating ORIENTATION-HORIZONTAL TRUE 0) (gimp-layer-translate layerFloating trans 0) (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) insert by karlhof26 (gimp-displays-flush) (gimp-item-transform-rotate-simple layerFloating ROTATE-90 TRUE 0 0) (gimp-layer-translate layerFloating trans 0) (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) (gimp-item-transform-flip-simple layerFloating ORIENTATION-HORIZONTAL TRUE 0) (gimp-item-transform-rotate-simple layerFloating ROTATE-90 TRUE 0 0) (gimp-layer-translate layerFloating trans trans) (gimp-displays-flush) (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) (gimp-item-transform-rotate-simple layerFloating ROTATE-180 TRUE 0 0) (gimp-layer-translate layerFloating trans trans) (gimp-displays-flush) (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) (gimp-item-transform-flip-simple layerFloating ORIENTATION-HORIZONTAL TRUE 0) (gimp-item-transform-rotate-simple layerFloating ROTATE-180 TRUE 0 0) (gimp-layer-translate layerFloating 0 trans) (gimp-displays-flush) (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) (gimp-item-transform-rotate-simple layerFloating ROTATE-270 TRUE 0 0) (gimp-layer-translate layerFloating 0 trans) (gimp-image-select-polygon image CHANNEL-OP-REPLACE 6 (vector 0 0 sel sel sel 0)) (gimp-edit-copy layerBase) (set! layerFloating (car (gimp-edit-paste layerComplete FALSE))) (gimp-item-transform-flip-simple layerFloating ORIENTATION-HORIZONTAL TRUE 0) (gimp-item-transform-rotate-simple layerFloating ROTATE-270 TRUE 0 0) (gimp-floating-sel-anchor layerFloating) (gimp-displays-flush) (if flip (gimp-image-flip image ORIENTATION-HORIZONTAL) ) (if (= rotate 1) (gimp-image-rotate image ROTATE-270) ) (if (= rotate 2) (gimp-image-rotate image ROTATE-180) ) (if (= rotate 3) (gimp-image-rotate image ROTATE-90) ) (gimp-displays-flush) (if (> blend 0) (begin (gimp-selection-all image) (gimp-selection-shrink image (ceiling (/ blend 2))) (gimp-selection-feather image blend) rows added by karlhof26 (gimp-selection-invert image) (gimp-edit-clear layerComplete) (gimp-selection-none image) ) ) (gimp-displays-flush) (if (or (not (= tilesX 1)) (not (= tilesY 1))) (begin (gimp-image-undo-group-end image) (gimp-image-undo-group-start image) (set! layerBase (car (gimp-image-merge-down image layerComplete CLIP-TO-IMAGE))) (script-fu-tile-random-rotation image layerBase tilesX tilesY TRUE TRUE) ) ) (gimp-image-undo-group-end image) (gimp-displays-flush) (gimp-context-pop) ) ) (script-fu-register "script-fu-make-rotationally-seamless" "Make _rotationally seamless..." "Copy, rotate, and flip half of one edge of the image around its border. \nfile:make-rotationally-seamless.scm" "John Tasto <>" "John Tasto" "2015/03/03" "RGB* GRAY* INDEXED*" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0 SF-OPTION _"Side to duplicate" '("Top left" "Top right" "Bottom left" "Bottom right" "Left top" "Left bottom" "Right top" "Right bottom") SF-ADJUSTMENT "Blend width (0 for full)" '(0 0 1024 1 8 0 SF-SPINNER) SF-ADJUSTMENT "Preview X tiles" '(1 1 256 1 1 0 SF-SPINNER) SF-ADJUSTMENT "Preview Y tiles" '(1 1 256 1 1 0 SF-SPINNER) ) (script-fu-menu-register "script-fu-make-rotationally-seamless" "<Image>/Script-Fu2/Pattern")
d28d7ec2a52b078a7176949f96e11012767be835ac79ebc512c9afc9c71a8100
dnadales/sandbox
Transaction.hs
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE OverloadedLists # {-# LANGUAGE TypeOperators #-} module ChimericLedgers.Transaction where import Data.Set (Set) import qualified Data.Set as Set import Data.Word (Word32) import ChimericLedgers.Address import ChimericLedgers.Value data UtxoTx = UtxoTx { inputs :: Set Input , outputs :: [Output] , forge :: Value , fee :: Value } deriving (Eq, Ord, Show) newtype Id = Id UtxoTx deriving (Eq, Ord, Show) -- | @hash c@ is (should be) the cryptographic collision-resistant hash of object -- hash :: UtxoTx -> Id hash = Id inputsList :: UtxoTx -> [Input] inputsList = Set.toList . inputs data Input = Input { -- | Id of the previous transaction to which this input refers. tid :: Id -- | Index within the transaction referred by 'tid' that refers to the -- output that should be spent. , index :: Int } deriving (Eq, Ord, Show) (@@) :: UtxoTx -> Int -> Input t @@ i = Input (hash t) i data Output = Output { -- | Address that owns the value. address :: Address , value :: Value } deriving (Eq, Ord, Show) ($-->@) :: Value -> Address -> Output v $-->@ a = Output a v -- | Calculate the unspent outputs, by calculating a set of inputs that hold a -- reference to the unspent transactions. unspentOuts :: UtxoTx -> Set Input unspentOuts t = Set.fromList $ fmap (uncurry Input) $ zip tHashes [0..] where tHashes = replicate (length (outputs t)) (hash t) -- | Outputs spent by a transaction. This is just the set of inputs. spentOuts :: UtxoTx -> Set Input spentOuts = inputs -------------------------------------------------------------------------------- -- Examples -------------------------------------------------------------------------------- t1 :: UtxoTx t1 = UtxoTx { inputs = [] > @ 1 ] , forge = 1000 , fee = 0 } t2 :: UtxoTx t2 = UtxoTx { inputs = [t1 @@ 0] > @ 2 , 200 $ -->@ 1 ] , forge = 0 , fee = 0 } t3 :: UtxoTx t3 = UtxoTx { inputs = [t2 @@ 1] > @ 3 ] , forge = 0 , fee = 1 } t4 :: UtxoTx t4 = UtxoTx { inputs = [t3 @@ 0] > @ 2 ] -- The total amount we can spend is : 199 + 10 - 2 , forge = 10 -- On this model, the money that is forged can be spent on any output. , fee = 2 } t5 :: UtxoTx t5 = UtxoTx { inputs = [t4 @@ 0, t2 @@ 0] > @ 2 , 500 $ -->@ 3 ] , forge = 0 , fee = 7 } t6 :: UtxoTx t6 = UtxoTx { inputs = [t5 @@ 0, t5 @@ 1] > @ 3 ] , forge = 0 , fee = 1 } -- TODO: -- Add some tests ghci > isValid [ t1 , t2 , t3 , t4 , t5 ] t6 -- [ t1 , t2 , t3 , t4 , t5 t6 ]
null
https://raw.githubusercontent.com/dnadales/sandbox/401c4f0fac5f8044fb6e2e443bacddce6f135b4b/chimeric-ledgers/src/ChimericLedgers/Transaction.hs
haskell
# LANGUAGE TypeOperators # | @hash c@ is (should be) the cryptographic collision-resistant hash of | Id of the previous transaction to which this input refers. | Index within the transaction referred by 'tid' that refers to the output that should be spent. | Address that owns the value. >@) :: Value -> Address -> Output >@ a = Output a v | Calculate the unspent outputs, by calculating a set of inputs that hold a reference to the unspent transactions. | Outputs spent by a transaction. This is just the set of inputs. ------------------------------------------------------------------------------ Examples ------------------------------------------------------------------------------ >@ 1 ] The total amount we can spend is : 199 + 10 - 2 On this model, the money that is forged can be spent on any output. >@ 3 ] TODO: Add some tests
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE OverloadedLists # module ChimericLedgers.Transaction where import Data.Set (Set) import qualified Data.Set as Set import Data.Word (Word32) import ChimericLedgers.Address import ChimericLedgers.Value data UtxoTx = UtxoTx { inputs :: Set Input , outputs :: [Output] , forge :: Value , fee :: Value } deriving (Eq, Ord, Show) newtype Id = Id UtxoTx deriving (Eq, Ord, Show) object hash :: UtxoTx -> Id hash = Id inputsList :: UtxoTx -> [Input] inputsList = Set.toList . inputs data Input = Input tid :: Id , index :: Int } deriving (Eq, Ord, Show) (@@) :: UtxoTx -> Int -> Input t @@ i = Input (hash t) i data Output = Output address :: Address , value :: Value } deriving (Eq, Ord, Show) unspentOuts :: UtxoTx -> Set Input unspentOuts t = Set.fromList $ fmap (uncurry Input) $ zip tHashes [0..] where tHashes = replicate (length (outputs t)) (hash t) spentOuts :: UtxoTx -> Set Input spentOuts = inputs t1 :: UtxoTx t1 = UtxoTx { inputs = [] > @ 1 ] , forge = 1000 , fee = 0 } t2 :: UtxoTx t2 = UtxoTx { inputs = [t1 @@ 0] , forge = 0 , fee = 0 } t3 :: UtxoTx t3 = UtxoTx { inputs = [t2 @@ 1] > @ 3 ] , forge = 0 , fee = 1 } t4 :: UtxoTx t4 = UtxoTx { inputs = [t3 @@ 0] , fee = 2 } t5 :: UtxoTx t5 = UtxoTx { inputs = [t4 @@ 0, t2 @@ 0] , forge = 0 , fee = 7 } t6 :: UtxoTx t6 = UtxoTx { inputs = [t5 @@ 0, t5 @@ 1] > @ 3 ] , forge = 0 , fee = 1 } ghci > isValid [ t1 , t2 , t3 , t4 , t5 ] t6 [ t1 , t2 , t3 , t4 , t5 t6 ]
fab499fddf055395102e334d6d0deb324464f32e9d937ca5bc115fb75f79185e
heshrobe/joshua-dist
noisy-or-nodes.lisp
-*- Mode : LISP ; Syntax : Common - Lisp ; Package : Ideal ; Base : 10 -*- (in-package :ideal) ;;;;******************************************************** Copyright ( c ) 1989 , 1992 Rockwell International -- All rights reserved . Rockwell International Science Center Palo Alto Lab ;;;;******************************************************** Sampath ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; (eval-when (:compile-toplevel :load-toplevel :execute) (export '(NOISY-OR-NODE-P NOISY-OR-SUBTYPE CONVERT-NOISY-OR-NODE-TO-CHANCE-NODE CONVERT-CHANCE-NODE-TO-NOISY-OR-NODE INHIBITOR-PROB-OF NOISY-OR-DET-FN-OF COMPILE-NOISY-OR-DISTRIBUTION NOISY-OR-FALSE-CASE-P CONVERT-NOISY-OR-NODE-TO-SUBTYPE))) ;----------------------------------------------------------------------------------------- ;---------- ABSTRACT data structure level ---------------------------------------- ;----------------------------------------------------------------------------------------- (defun noisy-or-node-p (node) (and (chance-node-p node) (discrete-dist-noisy-or-p (node-distribution node)))) (defun noisy-or-subtype (node) (discrete-dist-noisy-or-subtype (node-distribution node))) (defun set-noisy-or-subtype (node val) ; Also allows the subtype to be set to NIL to account for the case ; where one is unsetting the subtype, i,e, converting the noisy-or ; node to a chance node. (or (null val) (ecase val (:BINARY)(:NARY)(:GENERIC))) (setf (discrete-dist-noisy-or-subtype (node-distribution node)) val)) (defsetf noisy-or-subtype set-noisy-or-subtype) ;-------------------------------------------------------- (defun set-noisy-or-flag (node &key subtype) (cond ((not (chance-node-p node)) (error "Cant set Noisy Or flag for node ~A since its not a chance node" node)) (t (setf (discrete-dist-noisy-or-p (node-distribution node)) t) (setf (noisy-or-subtype node) subtype)))) (defun unset-noisy-or-flag (node) (cond ((not (chance-node-p node)) (error "Cant set Noisy Or flag for node ~A since its not a chance node" node)) (t (setf (discrete-dist-noisy-or-p (node-distribution node)) nil) (setf (noisy-or-subtype node) nil) (setf (discrete-dist-noisy-or-info (node-distribution node)) nil)))) ;--- ; When calling this function all other internal state in the node is in ; a consistent state and so we just switch the type. ; (This 'consistent state' ensured by careful coding -- basiclly the ; thing to note is to always compile the noisy or distribution after it ; changes in any way -- for eg in add-arcs) (defun convert-noisy-or-node-to-chance-node (n) (when (noisy-or-node-p n) (ideal-debug-msg "~%Converting ~A noisy or node ~A to a chance node" (noisy-or-subtype n) n) (unset-noisy-or-flag n)) (values n)) (defun convert-noisy-or-nodes-to-chance-nodes (diagram) (dolist (n diagram) (convert-noisy-or-node-to-chance-node n))) ; Converts a chance to node to a noisy-or node of type :BINARY (if it has two states ) or of type : otherwise . If the chance node is a deterministic chance node then it is converted to be a : GENERIC ; noisy-or node with the det function being the same as the deterministi ; chance node's det function. (defun set-noisy-or-det-fn-of (node pred-case value) (write-probability-array (noisy-or-det-fn-array (discrete-dist-noisy-or-info (node-distribution node))) pred-case (node-predecessors node) value)) (defsetf noisy-or-det-fn-of set-noisy-or-det-fn-of) (defun convert-chance-node-to-noisy-or-node (n) (cond ((not (chance-node-p n)) (error "Cannot convert ~A to noisy-or node since it is of type ~A, not :CHANCE" n (node-type n))) (t ; Sets the noisy or flag (setf (discrete-dist-noisy-or-p (node-distribution n)) t) (cond ((deterministic-node-p n) (let ((det-fn-array (distribution-repn n))) (setf (noisy-or-subtype n) :GENERIC) (setf (relation-type n) :PROB) (create-empty-distribution n) (for-all-cond-cases (pred-case (node-predecessors n)) (setf (noisy-or-det-fn-of n pred-case) (contents-of-det-array-location det-fn-array pred-case (node-predecessors n)))))) ((probabilistic-node-p n) (setf (noisy-or-subtype n) (if (= (number-of-states n) 2) :BINARY :NARY)) (create-empty-distribution n) (set-noisy-or-det-fn-to-standard-nary-or-fn n)) (t (error "Node ~A is neither deterministic or probabilistic" n))) ; Compile the distribution (compile-noisy-or-distribution n) (values n)))) ;----------------------- (defun create-empty-noisy-or-distribution (node &key (default-inhibitor-prob 0)) (labels ((create-prob-list-for-predecessor (p) (mapcar #'(lambda (s)(cons s default-inhibitor-prob)) (state-labels p))) (make-inhibitor-prob-structure (node) (mapcar #'(lambda (p)(cons p (create-prob-list-for-predecessor p))) (node-predecessors node)))) (setf (discrete-dist-noisy-or-info (node-distribution node)) (make-noisy-or :inhibitor-probs (make-inhibitor-prob-structure node) :det-fn-array (make-probability-array (node-predecessors node) :element-type 'LABEL :initial-element (make-label :name 'DUMMY)) ; This field is purely so that a visible backpointer is available ; during debugging. Is not actually used by the code at all. :owner-node node)) (values))) (defun get-noisy-or-info (node) (discrete-dist-noisy-or-info (node-distribution node))) ; Returns the pair state.prob if found or :NO-ENTRY if error-mode is ; nil. If not an error. (defun get-noisy-or-inhibitor-prob-entry (noisy-or-info pred-case &key (error-mode t)) (cond ((not (exactly-one pred-case)) (error "~A should be a conditioning case containing exactly one node state pair" pred-case)) (t (or (assoc (state-in pred-case) (cdr (assoc (node-in pred-case) (noisy-or-inhibitor-probs noisy-or-info)))) (if (not error-mode) :NO-ENTRY) (error "No entry inhibitor prob of ~A in ~A" pred-case noisy-or-info))))) ;------------------------------- (defun inhibitor-prob-of (node pred-case) (cdr (get-noisy-or-inhibitor-prob-entry (discrete-dist-noisy-or-info (node-distribution node)) pred-case))) (defun set-inhibitor-prob-of (node pred-case value) (setf (cdr (get-noisy-or-inhibitor-prob-entry (discrete-dist-noisy-or-info (node-distribution node)) pred-case)) value)) (defsetf inhibitor-prob-of set-inhibitor-prob-of) ; If entry is not found and non-nil default is specified then default is ; returned. No entry and no default causes an error. (defun get-inhibitor-prob-from-noisy-or-info (noisy-or-info pred-case &key default) (let ((entry (get-noisy-or-inhibitor-prob-entry noisy-or-info pred-case :error-mode nil))) (cond ((eq entry :NO-ENTRY) (or default (error "No entry for ~A in ~A and no default specified" pred-case noisy-or-info))) (t (cdr entry))))) ;--------------------------- (defun noisy-or-det-fn-of (node pred-case) (get-det-fn-value-from-noisy-or-info (discrete-dist-noisy-or-info (node-distribution node)) (node-predecessors node) pred-case)) ; This Additional level of indirection is because this function is used ; to retrieve information from the previous det fn array when modifying ; the det fn array in diagram editing functions like add-arcs, delete-arcs, ; add-state etc. (defun get-det-fn-value-from-noisy-or-info (noisy-or-info predecessors pred-case) (read-probability-array (noisy-or-det-fn-array noisy-or-info) pred-case predecessors)) ;------------------------------ ; Copies inhibitor probs from noisy-or-info into the present ; noisy-or-info of node. If values are not found for some location ; <default> is used instead if it is not nil, if <default> is nil an ; error is signalled. (defun copy-inhibitor-probs (node noisy-or-info &key (default nil)) (dolist (p (node-predecessors node)) (for-all-cond-cases (pred-case p) (setf (inhibitor-prob-of node pred-case) (get-inhibitor-prob-from-noisy-or-info noisy-or-info pred-case :default default))))) ;----------------------------------------------------------------------------------------- ;---------------------- High level ------------------------------------------------------- ;----------------------------------------------------------------------------------------- (defun compile-noisy-or-distribution (node) (for-all-cond-cases (u (node-predecessors node)) (for-all-cond-cases (x node) (setf (prob-of x u) 0)) (let (x x-case) (for-all-cond-cases (u-prime (node-predecessors node)) (setq x (noisy-or-det-fn-of node u-prime)) (setq x-case (make-conditioning-case (list (cons node x)))) (incf (prob-of x-case u) (calc-transformation-prob node u-prime u))))) (values nil)) ; Used for consistency checking only. Is much more inefficient to use ; this directly rather than to compile the table as above. (defun calc-noisy-or-prob-of (node-case cond-case) (let ((s (state-in node-case)) (n (node-in node-case)) (total 0)) (for-all-cond-cases (u-prime (node-predecessors n)) (when (eq (noisy-or-det-fn-of n u-prime) s) (incf total (calc-transformation-prob n u-prime cond-case)))) (values total))) ; Calculates the probability of conditoning case bold-u being ; transformed to conditioning case bold-u-prime taking into account both ; normal operation and failures of nodes. ; Note: in doing in the map to walk down both u-prime and u ; simultaneously, I am assuming that the order in which the nodes appear ; in u-prime and in u are the same. <individual-transformation-prob> ; relies on this prooperty (though it does make a check). ; The assumption is ok because of the implementation details of ; for-all-cond-cases but it bears explicit mentioning since it is an ; implementation dependant hack. (defun calc-transformation-prob (node bold-u-prime bold-u) (multiply-over ((u-prime bold-u-prime)(u bold-u)) (individual-transformation-prob node u-prime u))) (defun individual-transformation-prob (node u-prime u) (let ((u-prime-node (car u-prime)) (u-prime-state (cdr u-prime)) (u-node (car u)) (u-state (cdr u))) (unless (eq u-prime-node u-node) (error "Program error. The node in u-prime, ~A and in u, ~A should be the same. See comments near this function's definition. Needs debugging." u-prime-node u-node)) (cond ((eq u-state u-prime-state) (+ (prob-of-all-inhibitors-being-normal node u-node) (inhibitor-prob-of node (make-conditioning-case (list u-prime))))) (t (inhibitor-prob-of node (make-conditioning-case (list u-prime))))))) ; Could have cached this 'normal' probability in the data structure ; but what the heck, this is a"compile time" step and so we can be ; a little inefficient. (defun prob-of-all-inhibitors-being-normal (node predecessor) (let ((total-failure-prob 0)) (for-all-cond-cases (pred-case predecessor) (incf total-failure-prob (inhibitor-prob-of node pred-case))) (values (- 1 total-failure-prob)))) ;---------------------------- (defun find-label-numbered (node m) (or (find m (state-labels node) :key #'label-id-number :test #'=) (error "Could not find label numbered ~A of node ~A" m node))) (defun generalized-nary-or-function (node pred-case) (labels ((largest-state-number (n) (- (number-of-states n) 1)) (ratio (n m) (if (zerop n) 0 (/ n m)))) (find-label-numbered node (ceiling (* (ratio (sum-over (pred.state pred-case) (ratio (label-id-number (cdr pred.state))(largest-state-number (car pred.state)))) (number-of-predecessors node)) (largest-state-number node)))))) (defun set-noisy-or-det-fn-to-standard-nary-or-fn (node) (for-all-cond-cases (case (node-predecessors node)) (setf (noisy-or-det-fn-of node case) (generalized-nary-or-function node case)))) (defun set-noisy-or-det-fn-randomly (node) (let ((random-state (first (state-labels node)))) (for-all-cond-cases (case (node-predecessors node)) (setf (noisy-or-det-fn-of node case) random-state)))) ; This function and immediate following functions are temporary and not necessary for IDEAL to function . used for examples for the Noisy Or paper . (defun reset-noisy-or-det-fn (node function) (for-all-cond-cases (case (node-predecessors node)) (setf (noisy-or-det-fn-of node case) (find-label-numbered node (apply function (mapcar #'(lambda (n.s)(label-id-number (cdr n.s))) case))))) ; The following call takes care of recompiling the distribution too. (convert-noisy-or-node-to-subtype node :GENERIC)) (defun and-f (&rest args) (cond ((not (every #'(lambda (a)(and (numberp a)(or (= a 0)(= a 1)))) args)) (error "Incorrect argument pattern ~A" args)) (t (if (every #'(lambda (a) (= a 1)) args) 1 0)))) (defun xor-f (&rest args) (cond ((not (every #'(lambda (a)(and (numberp a)(or (= a 0)(= a 1)))) args)) (error "Incorrect argument pattern ~A" args)) ((not (= (length args) 2)) (error "Incorrect arg pattern")) (t (if (= (apply #'+ args) 1) 1 0)))) (defun or-f (&rest args) (cond ((not (every #'(lambda (a)(and (numberp a)(or (= a 0)(= a 1)))) args)) (error "Incorrect argument pattern ~A" args)) (t (if (some #'(lambda (a) (= a 1)) args) 1 0)))) (defun add-f (&rest args) (cond ((not (every #'(lambda (a)(numberp a)) args)) (error "Incorrect argument pattern ~A" args)) (t (apply #'+ args)))) ;-------------------------------------- (defun noisy-or-false-case-p (node-case) (= (label-id-number (state-in node-case)) 0)) (defun conv (node) (convert-noisy-or-node-to-subtype node :GENERIC) (dolist (s (state-labels node)) (setf (label-name s) (ecase (label-name s) (:TRUE :S-0) (:FALSE :S-1)))) (add-state node :S-2) (add-state node :S-3) (reset-noisy-or-det-fn node #'add-f)) ;------------------------------------------ (defun convert-noisy-or-node-to-subtype (node new-subtype) (when (and (eq new-subtype :BINARY)(> (number-of-states node) 2)) (setq new-subtype :NARY)) (setf (noisy-or-subtype node) new-subtype) ; Make all inhibitor probs except for the false case 0 if the new type ; is binary. (when (eq new-subtype :BINARY) (dolist (p (node-predecessors node)) (for-all-cond-cases (pred-case p) (if (not (noisy-or-false-case-p pred-case)) (setf (inhibitor-prob-of node pred-case) 0))))) (ecase new-subtype ((:BINARY :NARY) (set-noisy-or-det-fn-to-standard-nary-or-fn node)) ((:GENERIC) ; Just let the old function be. ;;; (set-noisy-or-det-fn-randomly node) )) (compile-noisy-or-distribution node) (values node))
null
https://raw.githubusercontent.com/heshrobe/joshua-dist/f59f06303f9fabef3e945a920cf9a26d9c2fd55e/ideal/code/noisy-or-nodes.lisp
lisp
Syntax : Common - Lisp ; Package : Ideal ; Base : 10 -*- ******************************************************** ******************************************************** ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ----------------------------------------------------------------------------------------- ---------- ABSTRACT data structure level ---------------------------------------- ----------------------------------------------------------------------------------------- Also allows the subtype to be set to NIL to account for the case where one is unsetting the subtype, i,e, converting the noisy-or node to a chance node. -------------------------------------------------------- --- When calling this function all other internal state in the node is in a consistent state and so we just switch the type. (This 'consistent state' ensured by careful coding -- basiclly the thing to note is to always compile the noisy or distribution after it changes in any way -- for eg in add-arcs) Converts a chance to node to a noisy-or node of type :BINARY (if it noisy-or node with the det function being the same as the deterministi chance node's det function. Sets the noisy or flag Compile the distribution ----------------------- This field is purely so that a visible backpointer is available during debugging. Is not actually used by the code at all. Returns the pair state.prob if found or :NO-ENTRY if error-mode is nil. If not an error. ------------------------------- If entry is not found and non-nil default is specified then default is returned. No entry and no default causes an error. --------------------------- This Additional level of indirection is because this function is used to retrieve information from the previous det fn array when modifying the det fn array in diagram editing functions like add-arcs, delete-arcs, add-state etc. ------------------------------ Copies inhibitor probs from noisy-or-info into the present noisy-or-info of node. If values are not found for some location <default> is used instead if it is not nil, if <default> is nil an error is signalled. ----------------------------------------------------------------------------------------- ---------------------- High level ------------------------------------------------------- ----------------------------------------------------------------------------------------- Used for consistency checking only. Is much more inefficient to use this directly rather than to compile the table as above. Calculates the probability of conditoning case bold-u being transformed to conditioning case bold-u-prime taking into account both normal operation and failures of nodes. Note: in doing in the map to walk down both u-prime and u simultaneously, I am assuming that the order in which the nodes appear in u-prime and in u are the same. <individual-transformation-prob> relies on this prooperty (though it does make a check). The assumption is ok because of the implementation details of for-all-cond-cases but it bears explicit mentioning since it is an implementation dependant hack. Could have cached this 'normal' probability in the data structure but what the heck, this is a"compile time" step and so we can be a little inefficient. ---------------------------- This function and immediate following functions are temporary and not necessary The following call takes care of recompiling the distribution too. -------------------------------------- ------------------------------------------ Make all inhibitor probs except for the false case 0 if the new type is binary. Just let the old function be. (set-noisy-or-det-fn-randomly node)
(in-package :ideal) Copyright ( c ) 1989 , 1992 Rockwell International -- All rights reserved . Rockwell International Science Center Palo Alto Lab (eval-when (:compile-toplevel :load-toplevel :execute) (export '(NOISY-OR-NODE-P NOISY-OR-SUBTYPE CONVERT-NOISY-OR-NODE-TO-CHANCE-NODE CONVERT-CHANCE-NODE-TO-NOISY-OR-NODE INHIBITOR-PROB-OF NOISY-OR-DET-FN-OF COMPILE-NOISY-OR-DISTRIBUTION NOISY-OR-FALSE-CASE-P CONVERT-NOISY-OR-NODE-TO-SUBTYPE))) (defun noisy-or-node-p (node) (and (chance-node-p node) (discrete-dist-noisy-or-p (node-distribution node)))) (defun noisy-or-subtype (node) (discrete-dist-noisy-or-subtype (node-distribution node))) (defun set-noisy-or-subtype (node val) (or (null val) (ecase val (:BINARY)(:NARY)(:GENERIC))) (setf (discrete-dist-noisy-or-subtype (node-distribution node)) val)) (defsetf noisy-or-subtype set-noisy-or-subtype) (defun set-noisy-or-flag (node &key subtype) (cond ((not (chance-node-p node)) (error "Cant set Noisy Or flag for node ~A since its not a chance node" node)) (t (setf (discrete-dist-noisy-or-p (node-distribution node)) t) (setf (noisy-or-subtype node) subtype)))) (defun unset-noisy-or-flag (node) (cond ((not (chance-node-p node)) (error "Cant set Noisy Or flag for node ~A since its not a chance node" node)) (t (setf (discrete-dist-noisy-or-p (node-distribution node)) nil) (setf (noisy-or-subtype node) nil) (setf (discrete-dist-noisy-or-info (node-distribution node)) nil)))) (defun convert-noisy-or-node-to-chance-node (n) (when (noisy-or-node-p n) (ideal-debug-msg "~%Converting ~A noisy or node ~A to a chance node" (noisy-or-subtype n) n) (unset-noisy-or-flag n)) (values n)) (defun convert-noisy-or-nodes-to-chance-nodes (diagram) (dolist (n diagram) (convert-noisy-or-node-to-chance-node n))) has two states ) or of type : otherwise . If the chance node is a deterministic chance node then it is converted to be a : GENERIC (defun set-noisy-or-det-fn-of (node pred-case value) (write-probability-array (noisy-or-det-fn-array (discrete-dist-noisy-or-info (node-distribution node))) pred-case (node-predecessors node) value)) (defsetf noisy-or-det-fn-of set-noisy-or-det-fn-of) (defun convert-chance-node-to-noisy-or-node (n) (cond ((not (chance-node-p n)) (error "Cannot convert ~A to noisy-or node since it is of type ~A, not :CHANCE" n (node-type n))) (setf (discrete-dist-noisy-or-p (node-distribution n)) t) (cond ((deterministic-node-p n) (let ((det-fn-array (distribution-repn n))) (setf (noisy-or-subtype n) :GENERIC) (setf (relation-type n) :PROB) (create-empty-distribution n) (for-all-cond-cases (pred-case (node-predecessors n)) (setf (noisy-or-det-fn-of n pred-case) (contents-of-det-array-location det-fn-array pred-case (node-predecessors n)))))) ((probabilistic-node-p n) (setf (noisy-or-subtype n) (if (= (number-of-states n) 2) :BINARY :NARY)) (create-empty-distribution n) (set-noisy-or-det-fn-to-standard-nary-or-fn n)) (t (error "Node ~A is neither deterministic or probabilistic" n))) (compile-noisy-or-distribution n) (values n)))) (defun create-empty-noisy-or-distribution (node &key (default-inhibitor-prob 0)) (labels ((create-prob-list-for-predecessor (p) (mapcar #'(lambda (s)(cons s default-inhibitor-prob)) (state-labels p))) (make-inhibitor-prob-structure (node) (mapcar #'(lambda (p)(cons p (create-prob-list-for-predecessor p))) (node-predecessors node)))) (setf (discrete-dist-noisy-or-info (node-distribution node)) (make-noisy-or :inhibitor-probs (make-inhibitor-prob-structure node) :det-fn-array (make-probability-array (node-predecessors node) :element-type 'LABEL :initial-element (make-label :name 'DUMMY)) :owner-node node)) (values))) (defun get-noisy-or-info (node) (discrete-dist-noisy-or-info (node-distribution node))) (defun get-noisy-or-inhibitor-prob-entry (noisy-or-info pred-case &key (error-mode t)) (cond ((not (exactly-one pred-case)) (error "~A should be a conditioning case containing exactly one node state pair" pred-case)) (t (or (assoc (state-in pred-case) (cdr (assoc (node-in pred-case) (noisy-or-inhibitor-probs noisy-or-info)))) (if (not error-mode) :NO-ENTRY) (error "No entry inhibitor prob of ~A in ~A" pred-case noisy-or-info))))) (defun inhibitor-prob-of (node pred-case) (cdr (get-noisy-or-inhibitor-prob-entry (discrete-dist-noisy-or-info (node-distribution node)) pred-case))) (defun set-inhibitor-prob-of (node pred-case value) (setf (cdr (get-noisy-or-inhibitor-prob-entry (discrete-dist-noisy-or-info (node-distribution node)) pred-case)) value)) (defsetf inhibitor-prob-of set-inhibitor-prob-of) (defun get-inhibitor-prob-from-noisy-or-info (noisy-or-info pred-case &key default) (let ((entry (get-noisy-or-inhibitor-prob-entry noisy-or-info pred-case :error-mode nil))) (cond ((eq entry :NO-ENTRY) (or default (error "No entry for ~A in ~A and no default specified" pred-case noisy-or-info))) (t (cdr entry))))) (defun noisy-or-det-fn-of (node pred-case) (get-det-fn-value-from-noisy-or-info (discrete-dist-noisy-or-info (node-distribution node)) (node-predecessors node) pred-case)) (defun get-det-fn-value-from-noisy-or-info (noisy-or-info predecessors pred-case) (read-probability-array (noisy-or-det-fn-array noisy-or-info) pred-case predecessors)) (defun copy-inhibitor-probs (node noisy-or-info &key (default nil)) (dolist (p (node-predecessors node)) (for-all-cond-cases (pred-case p) (setf (inhibitor-prob-of node pred-case) (get-inhibitor-prob-from-noisy-or-info noisy-or-info pred-case :default default))))) (defun compile-noisy-or-distribution (node) (for-all-cond-cases (u (node-predecessors node)) (for-all-cond-cases (x node) (setf (prob-of x u) 0)) (let (x x-case) (for-all-cond-cases (u-prime (node-predecessors node)) (setq x (noisy-or-det-fn-of node u-prime)) (setq x-case (make-conditioning-case (list (cons node x)))) (incf (prob-of x-case u) (calc-transformation-prob node u-prime u))))) (values nil)) (defun calc-noisy-or-prob-of (node-case cond-case) (let ((s (state-in node-case)) (n (node-in node-case)) (total 0)) (for-all-cond-cases (u-prime (node-predecessors n)) (when (eq (noisy-or-det-fn-of n u-prime) s) (incf total (calc-transformation-prob n u-prime cond-case)))) (values total))) (defun calc-transformation-prob (node bold-u-prime bold-u) (multiply-over ((u-prime bold-u-prime)(u bold-u)) (individual-transformation-prob node u-prime u))) (defun individual-transformation-prob (node u-prime u) (let ((u-prime-node (car u-prime)) (u-prime-state (cdr u-prime)) (u-node (car u)) (u-state (cdr u))) (unless (eq u-prime-node u-node) (error "Program error. The node in u-prime, ~A and in u, ~A should be the same. See comments near this function's definition. Needs debugging." u-prime-node u-node)) (cond ((eq u-state u-prime-state) (+ (prob-of-all-inhibitors-being-normal node u-node) (inhibitor-prob-of node (make-conditioning-case (list u-prime))))) (t (inhibitor-prob-of node (make-conditioning-case (list u-prime))))))) (defun prob-of-all-inhibitors-being-normal (node predecessor) (let ((total-failure-prob 0)) (for-all-cond-cases (pred-case predecessor) (incf total-failure-prob (inhibitor-prob-of node pred-case))) (values (- 1 total-failure-prob)))) (defun find-label-numbered (node m) (or (find m (state-labels node) :key #'label-id-number :test #'=) (error "Could not find label numbered ~A of node ~A" m node))) (defun generalized-nary-or-function (node pred-case) (labels ((largest-state-number (n) (- (number-of-states n) 1)) (ratio (n m) (if (zerop n) 0 (/ n m)))) (find-label-numbered node (ceiling (* (ratio (sum-over (pred.state pred-case) (ratio (label-id-number (cdr pred.state))(largest-state-number (car pred.state)))) (number-of-predecessors node)) (largest-state-number node)))))) (defun set-noisy-or-det-fn-to-standard-nary-or-fn (node) (for-all-cond-cases (case (node-predecessors node)) (setf (noisy-or-det-fn-of node case) (generalized-nary-or-function node case)))) (defun set-noisy-or-det-fn-randomly (node) (let ((random-state (first (state-labels node)))) (for-all-cond-cases (case (node-predecessors node)) (setf (noisy-or-det-fn-of node case) random-state)))) for IDEAL to function . used for examples for the Noisy Or paper . (defun reset-noisy-or-det-fn (node function) (for-all-cond-cases (case (node-predecessors node)) (setf (noisy-or-det-fn-of node case) (find-label-numbered node (apply function (mapcar #'(lambda (n.s)(label-id-number (cdr n.s))) case))))) (convert-noisy-or-node-to-subtype node :GENERIC)) (defun and-f (&rest args) (cond ((not (every #'(lambda (a)(and (numberp a)(or (= a 0)(= a 1)))) args)) (error "Incorrect argument pattern ~A" args)) (t (if (every #'(lambda (a) (= a 1)) args) 1 0)))) (defun xor-f (&rest args) (cond ((not (every #'(lambda (a)(and (numberp a)(or (= a 0)(= a 1)))) args)) (error "Incorrect argument pattern ~A" args)) ((not (= (length args) 2)) (error "Incorrect arg pattern")) (t (if (= (apply #'+ args) 1) 1 0)))) (defun or-f (&rest args) (cond ((not (every #'(lambda (a)(and (numberp a)(or (= a 0)(= a 1)))) args)) (error "Incorrect argument pattern ~A" args)) (t (if (some #'(lambda (a) (= a 1)) args) 1 0)))) (defun add-f (&rest args) (cond ((not (every #'(lambda (a)(numberp a)) args)) (error "Incorrect argument pattern ~A" args)) (t (apply #'+ args)))) (defun noisy-or-false-case-p (node-case) (= (label-id-number (state-in node-case)) 0)) (defun conv (node) (convert-noisy-or-node-to-subtype node :GENERIC) (dolist (s (state-labels node)) (setf (label-name s) (ecase (label-name s) (:TRUE :S-0) (:FALSE :S-1)))) (add-state node :S-2) (add-state node :S-3) (reset-noisy-or-det-fn node #'add-f)) (defun convert-noisy-or-node-to-subtype (node new-subtype) (when (and (eq new-subtype :BINARY)(> (number-of-states node) 2)) (setq new-subtype :NARY)) (setf (noisy-or-subtype node) new-subtype) (when (eq new-subtype :BINARY) (dolist (p (node-predecessors node)) (for-all-cond-cases (pred-case p) (if (not (noisy-or-false-case-p pred-case)) (setf (inhibitor-prob-of node pred-case) 0))))) (ecase new-subtype ((:BINARY :NARY) (set-noisy-or-det-fn-to-standard-nary-or-fn node)) )) (compile-noisy-or-distribution node) (values node))
a66711a1e6637f548ea867952ca5854e7a4515cf10421f3ddbcca2bcf33a3758
jserot/caph
arrays.ml
(************************************************************************************) (* *) (* CAPH *) (* -bpclermont.fr *) (* *) (* *) (* *) Copyright 2011 - 2019 . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (************************************************************************************) module Array1 = struct type 'a t = 'a array exception Invalid_index of int exception Invalid_size let make n v = Array.make n v let init n f = Array.init n f let copy a = Array.copy a let size a = Array.length a let get a i = try a.(i) with Invalid_argument _ -> raise (Invalid_index i) let set a i v = try a.(i) <- v with Invalid_argument _ -> raise (Invalid_index i) let of_list l = Array.of_list l let to_list a = Array.to_list a let iter f a = Array.iter f a let iteri f a = Array.iteri f a let map f a = Array.map f a let mapi f a = Array.mapi f a let to_string ?(ld="[") ?(rd="]") ?(sep=",") f a = ld ^ Misc.string_of_list f sep (to_list a) ^ rd end module Array2 = struct type 'a t = 'a array array exception Invalid_index of int * int exception Invalid_size let init (n1,n2) f = Array.init n1 (function i -> Array1.init n2 (f i)) let make (n1,n2) v = init (n1,n2) (fun i j -> v) let copy a = Array.init (Array.length a) (function i -> Array1.copy a.(i)) let size a = Array.length a, try Array.length a.(0) with Invalid_argument _ -> 0 let get a (i,j) = try a.(i).(j) with Invalid_argument _ -> raise (Invalid_index (i,j)) let set a (i,j) v = try a.(i).(j) <- v with Invalid_argument _ -> raise (Invalid_index (i,j)) let of_list ll = if Misc.list_same List.length ll then Array.of_list (List.map Array1.of_list ll) else raise Invalid_size let to_list a = List.map Array1.to_list (Array.to_list a) let iter f a = Array.iter (Array1.iter f) a let iteri f a = Array.iteri (fun i a' -> Array1.iteri (f i) a') a let map f a = Array.map (Array1.map f) a let to_string ?(ld="[") ?(rd="]") ?(sep=",") f a = ld ^ Misc.string_of_list (Array1.to_string ~ld:ld ~rd:rd ~sep:sep f) sep (Array1.to_list a) ^ rd end module Array3 = struct type 'a t = 'a array array array exception Invalid_index of int * int * int exception Invalid_size let init (n1,n2,n3) f = Array.init n1 (function i -> Array2.init (n2,n3) (f i)) let make (n1,n2,n3) v = init (n1,n2,n3) (fun i j k -> v) let copy a = Array.init (Array.length a) (function i -> Array2.copy a.(i)) let size a = Array.length a, (try Array.length a.(0) with Invalid_argument _ -> 0), (try Array.length a.(0).(0) with Invalid_argument _ -> 0) let get a (i,j,k) = try a.(i).(j).(k) with Invalid_argument _ -> raise (Invalid_index (i,j,k)) let set a (i,j,k) v = try a.(i).(j).(k) <- v with Invalid_argument _ -> raise (Invalid_index (i,j,k)) let of_list lll = if Misc.list_same List.length lll && Misc.list_same List.length (List.flatten lll) then Array.of_list (List.map Array2.of_list lll) else raise Invalid_size let to_list a = Array.to_list (Array.map Array2.to_list a) let iter f a = Array.iter (Array2.iter f) a let iteri f a = Array.iteri (fun i a' -> Array2.iteri (f i) a') a let map f a = Array.map (Array2.map f) a let map f a = Array.map (Array2.map f) a let to_string ?(ld="[") ?(rd="]") ?(sep=",") f a = ld ^ Misc.string_of_list (Array2.to_string ~ld:ld ~rd:rd ~sep:sep f) sep (Array1.to_list a) ^ rd end (* And so on.. *) Note 2016 - 05 - 19 , JS . An interesting question is whether this scheme can be generalized to provide * an implementation for n - D arrays .. * an implementation for n-D arrays .. *) Unfortunatly it ca n't . The idea would be to define a functor * module ( A : ARRAY ) = ( struct ... : ARRAY ) * taking a module implementing a n - D array and returning a module implementing a ( n+1)-D array , * where ARRAY would be the signature common to arrays of any dimension : * module type ARRAY = sig ... end * We would then define the implementation of an 1D array : * module Array1 = ( struct ... end : ARRAY ) * and then create 2D , 3D , .. arrays by simply applying the LiftDim functor : * module Array2 = LiftDim(Array1 ) * module Array3 = LiftDim(Array2 ) * etc .. * The problem is that we ca n't define such a common signature . * If we write * module type ARRAY = sig type ' a t = ' a array ... end * then we have to define as * module ( A : ARRAY ) = struct type ' a t = ' a array ... end * But then the signature of the input oand output modules do not match because type ' a t = ' a array is not included in type ' a t = ' a array * module LiftDim (A: ARRAY) = (struct ... : ARRAY) * taking a module implementing a n-D array and returning a module implementing a (n+1)-D array, * where ARRAY would be the signature common to arrays of any dimension : * module type ARRAY = sig ... end * We would then define the implementation of an 1D array : * module Array1 = (struct ... end : ARRAY) * and then create 2D, 3D, .. arrays by simply applying the LiftDim functor : * module Array2 = LiftDim(Array1) * module Array3 = LiftDim(Array2) * etc.. * The problem is that we can't define such a common signature. * If we write * module type ARRAY = sig type 'a t = 'a array ... end * then we have to define LiftDim as * module LiftDim (A: ARRAY) = struct type 'a t = 'a A.t array ... end * But then the signature of the input oand output modules do not match because type 'a t = 'a A.t array is not included in type 'a t = 'a array *)
null
https://raw.githubusercontent.com/jserot/caph/2b3b241f0c32aa4fcaf60d4b8529956cca8aa6b1/compiler/arrays.ml
ocaml
********************************************************************************** CAPH -bpclermont.fr ********************************************************************************** And so on..
Copyright 2011 - 2019 . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . module Array1 = struct type 'a t = 'a array exception Invalid_index of int exception Invalid_size let make n v = Array.make n v let init n f = Array.init n f let copy a = Array.copy a let size a = Array.length a let get a i = try a.(i) with Invalid_argument _ -> raise (Invalid_index i) let set a i v = try a.(i) <- v with Invalid_argument _ -> raise (Invalid_index i) let of_list l = Array.of_list l let to_list a = Array.to_list a let iter f a = Array.iter f a let iteri f a = Array.iteri f a let map f a = Array.map f a let mapi f a = Array.mapi f a let to_string ?(ld="[") ?(rd="]") ?(sep=",") f a = ld ^ Misc.string_of_list f sep (to_list a) ^ rd end module Array2 = struct type 'a t = 'a array array exception Invalid_index of int * int exception Invalid_size let init (n1,n2) f = Array.init n1 (function i -> Array1.init n2 (f i)) let make (n1,n2) v = init (n1,n2) (fun i j -> v) let copy a = Array.init (Array.length a) (function i -> Array1.copy a.(i)) let size a = Array.length a, try Array.length a.(0) with Invalid_argument _ -> 0 let get a (i,j) = try a.(i).(j) with Invalid_argument _ -> raise (Invalid_index (i,j)) let set a (i,j) v = try a.(i).(j) <- v with Invalid_argument _ -> raise (Invalid_index (i,j)) let of_list ll = if Misc.list_same List.length ll then Array.of_list (List.map Array1.of_list ll) else raise Invalid_size let to_list a = List.map Array1.to_list (Array.to_list a) let iter f a = Array.iter (Array1.iter f) a let iteri f a = Array.iteri (fun i a' -> Array1.iteri (f i) a') a let map f a = Array.map (Array1.map f) a let to_string ?(ld="[") ?(rd="]") ?(sep=",") f a = ld ^ Misc.string_of_list (Array1.to_string ~ld:ld ~rd:rd ~sep:sep f) sep (Array1.to_list a) ^ rd end module Array3 = struct type 'a t = 'a array array array exception Invalid_index of int * int * int exception Invalid_size let init (n1,n2,n3) f = Array.init n1 (function i -> Array2.init (n2,n3) (f i)) let make (n1,n2,n3) v = init (n1,n2,n3) (fun i j k -> v) let copy a = Array.init (Array.length a) (function i -> Array2.copy a.(i)) let size a = Array.length a, (try Array.length a.(0) with Invalid_argument _ -> 0), (try Array.length a.(0).(0) with Invalid_argument _ -> 0) let get a (i,j,k) = try a.(i).(j).(k) with Invalid_argument _ -> raise (Invalid_index (i,j,k)) let set a (i,j,k) v = try a.(i).(j).(k) <- v with Invalid_argument _ -> raise (Invalid_index (i,j,k)) let of_list lll = if Misc.list_same List.length lll && Misc.list_same List.length (List.flatten lll) then Array.of_list (List.map Array2.of_list lll) else raise Invalid_size let to_list a = Array.to_list (Array.map Array2.to_list a) let iter f a = Array.iter (Array2.iter f) a let iteri f a = Array.iteri (fun i a' -> Array2.iteri (f i) a') a let map f a = Array.map (Array2.map f) a let map f a = Array.map (Array2.map f) a let to_string ?(ld="[") ?(rd="]") ?(sep=",") f a = ld ^ Misc.string_of_list (Array2.to_string ~ld:ld ~rd:rd ~sep:sep f) sep (Array1.to_list a) ^ rd end Note 2016 - 05 - 19 , JS . An interesting question is whether this scheme can be generalized to provide * an implementation for n - D arrays .. * an implementation for n-D arrays .. *) Unfortunatly it ca n't . The idea would be to define a functor * module ( A : ARRAY ) = ( struct ... : ARRAY ) * taking a module implementing a n - D array and returning a module implementing a ( n+1)-D array , * where ARRAY would be the signature common to arrays of any dimension : * module type ARRAY = sig ... end * We would then define the implementation of an 1D array : * module Array1 = ( struct ... end : ARRAY ) * and then create 2D , 3D , .. arrays by simply applying the LiftDim functor : * module Array2 = LiftDim(Array1 ) * module Array3 = LiftDim(Array2 ) * etc .. * The problem is that we ca n't define such a common signature . * If we write * module type ARRAY = sig type ' a t = ' a array ... end * then we have to define as * module ( A : ARRAY ) = struct type ' a t = ' a array ... end * But then the signature of the input oand output modules do not match because type ' a t = ' a array is not included in type ' a t = ' a array * module LiftDim (A: ARRAY) = (struct ... : ARRAY) * taking a module implementing a n-D array and returning a module implementing a (n+1)-D array, * where ARRAY would be the signature common to arrays of any dimension : * module type ARRAY = sig ... end * We would then define the implementation of an 1D array : * module Array1 = (struct ... end : ARRAY) * and then create 2D, 3D, .. arrays by simply applying the LiftDim functor : * module Array2 = LiftDim(Array1) * module Array3 = LiftDim(Array2) * etc.. * The problem is that we can't define such a common signature. * If we write * module type ARRAY = sig type 'a t = 'a array ... end * then we have to define LiftDim as * module LiftDim (A: ARRAY) = struct type 'a t = 'a A.t array ... end * But then the signature of the input oand output modules do not match because type 'a t = 'a A.t array is not included in type 'a t = 'a array *)
73a4c000e7edcbb98565516f7d47e6911343c1da0d3c4100401423b72583d69c
PapenfussLab/bioshake
BWA.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} # LANGUAGE ViewPatterns # module Bioshake.Internal.BWA where import Bioshake hiding (C) import Bioshake.TH import Control.Monad.Trans (lift) import Data.List import Development.Shake import Development.Shake.FilePath import GHC.TypeLits data BWAOpts where K :: Int -> BWAOpts BW :: Int -> BWAOpts D :: Int -> BWAOpts R :: Double -> BWAOpts Y :: Int -> BWAOpts C :: Int -> BWAOpts DC :: Double -> BWAOpts W :: Int -> BWAOpts M :: Int -> BWAOpts RG :: String -> BWAOpts SoftClip :: BWAOpts instance Show BWAOpts where show (K p) = "-k" ++ show p show (BW p) = "-w" ++ show p show (D p) = "-d" ++ show p show (R p) = "-r" ++ show p show (Y p) = "-y" ++ show p show (C p) = "-c" ++ show p show (DC p) = "-D" ++ show p show (W p) = "-W" ++ show p show (M p) = "-m" ++ show p show (RG r) = concat ["-R", "'@RG\\tID:", r, "\\tSM:", r, "'"] show SoftClip = "-Y" k x = if x > 0 then K x else error "BWA: failed k > 0" bw x = if x > 0 then BW x else error "BWA: failed bw > 0" d x = if x > 0 then D x else error "BWA: failed d > 0" r x = if x > 0 then R x else error "BWA: failed r > 0" y x = if x > 0 then Y x else error "BWA: failed y > 0" c x = if x > 0 then C x else error "BWA: failed c > 0" dc x = if x > 0 then DC x else error "BWA: failed dc > 0" w x = if x > 0 then W x else error "BWA: failed w > 0" m x = if x > 0 then M x else error "BWA: failed m > 0" rg r = if r /= "" then RG r else error "BWA: require non-empty rg string" softClip = SoftClip data Align c = Align c [BWAOpts] deriving Show buildBWA t (Align _ opts) a@(paths -> inputs) [out] = if (length inputs > 2 || length inputs == 0) then error "BWA: need 1 single-end read set or 2 paired-end read sets" else do lift $ need [getRef a <.> ext | ext <- ["amb", "ann", "bwt", "pac", "sa"]] run "bwa mem" ["-t", show t] [getRef a] inputs (map show opts) "| samtools view -b" ">" out $(makeSingleTypes ''Align [''IsBam, ''NameSorted] [])
null
https://raw.githubusercontent.com/PapenfussLab/bioshake/afeb7219b171e242b6e9bb9e99e2f80c0a099aff/Bioshake/Internal/BWA.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeOperators #
# LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ViewPatterns # module Bioshake.Internal.BWA where import Bioshake hiding (C) import Bioshake.TH import Control.Monad.Trans (lift) import Data.List import Development.Shake import Development.Shake.FilePath import GHC.TypeLits data BWAOpts where K :: Int -> BWAOpts BW :: Int -> BWAOpts D :: Int -> BWAOpts R :: Double -> BWAOpts Y :: Int -> BWAOpts C :: Int -> BWAOpts DC :: Double -> BWAOpts W :: Int -> BWAOpts M :: Int -> BWAOpts RG :: String -> BWAOpts SoftClip :: BWAOpts instance Show BWAOpts where show (K p) = "-k" ++ show p show (BW p) = "-w" ++ show p show (D p) = "-d" ++ show p show (R p) = "-r" ++ show p show (Y p) = "-y" ++ show p show (C p) = "-c" ++ show p show (DC p) = "-D" ++ show p show (W p) = "-W" ++ show p show (M p) = "-m" ++ show p show (RG r) = concat ["-R", "'@RG\\tID:", r, "\\tSM:", r, "'"] show SoftClip = "-Y" k x = if x > 0 then K x else error "BWA: failed k > 0" bw x = if x > 0 then BW x else error "BWA: failed bw > 0" d x = if x > 0 then D x else error "BWA: failed d > 0" r x = if x > 0 then R x else error "BWA: failed r > 0" y x = if x > 0 then Y x else error "BWA: failed y > 0" c x = if x > 0 then C x else error "BWA: failed c > 0" dc x = if x > 0 then DC x else error "BWA: failed dc > 0" w x = if x > 0 then W x else error "BWA: failed w > 0" m x = if x > 0 then M x else error "BWA: failed m > 0" rg r = if r /= "" then RG r else error "BWA: require non-empty rg string" softClip = SoftClip data Align c = Align c [BWAOpts] deriving Show buildBWA t (Align _ opts) a@(paths -> inputs) [out] = if (length inputs > 2 || length inputs == 0) then error "BWA: need 1 single-end read set or 2 paired-end read sets" else do lift $ need [getRef a <.> ext | ext <- ["amb", "ann", "bwt", "pac", "sa"]] run "bwa mem" ["-t", show t] [getRef a] inputs (map show opts) "| samtools view -b" ">" out $(makeSingleTypes ''Align [''IsBam, ''NameSorted] [])
59f63ba77c0d6a42b2d03d7c7f32dae23dbdfdedc8e9ac64a9c677f82b680dd6
winny-/aoc
day14-original.rkt
#lang debug racket (require memo) (struct Input (polymer insertions) #:transparent) (define (read2 [ip (current-input-port)]) (let loop ([template #f] [insertions (hash)]) (match (read-line ip) [(? eof-object? e) (Input template insertions)] ["" (loop template insertions)] [(regexp "^[A-Z]+$" (list the-template)) (loop the-template insertions)] [(regexp "([A-Z]+) -> ([A-Z]+)" (list _ source dest)) (loop template (hash-set insertions source dest))]))) (define/memoize (step input) #:hash hash (match-define (struct Input (polymer insertions)) input) (define seq (sequence-map string (in-string polymer))) (for/fold ([acc (substring polymer 0 1)] #:result (Input acc insertions)) ([p seq] [q (sequence-tail seq 1)]) (string-append acc (hash-ref insertions (string-append p q) (const "")) q))) (define (histogram seq) (for/fold ([hist (hash)]) ([v seq]) (hash-update hist v add1 (const 0)))) (define (part1_b input) (go input 10)) (define (part1 input) (define final (for/fold ([acc input]) ([n (in-range 1 (add1 10))]) (match-define (and stepped (struct Input (poylmer _))) (step acc)) ;; (printf "~a: ~a\n" n poylmer) stepped)) (define hist (histogram (in-string (Input-polymer final)))) (- (argmax identity (hash-values hist)) (argmin identity (hash-values hist)))) (define memo (hash)) (define (go input n) (match-define (struct Input (polymer insertions)) input) (define seq (sequence-map string (in-string polymer))) (define hist (histogram (in-string (for/fold ([s input] #:result (histogram (in-string s))) ([p seq] [q (sequence-tail seq 1)]) (step (Input (string-append p q) insertions)))))) (- (argmax identity (hash-values hist)) (argmin identity (hash-values hist))) ) (define (part2 input) (define final (for/fold ([acc input]) ([n (in-range 1 (add1 40))]) (match-define (and stepped (struct Input (poylmer _))) (step acc)) (printf "Step ~a\n" n) stepped)) (define hist (histogram (in-string (Input-polymer final)))) (- (argmax identity (hash-values hist)) (argmin identity (hash-values hist))) ( go input 40 ) ) (module+ main (define input (read2)) (part1 input) (part2 input)) ;; Local Variables: ;; compile-command: "racket day14.rkt < sample.txt" ;; End:
null
https://raw.githubusercontent.com/winny-/aoc/fb8a3b9452224e6de1adcee8e2aecabda771345b/2021/day14/day14-original.rkt
racket
(printf "~a: ~a\n" n poylmer) Local Variables: compile-command: "racket day14.rkt < sample.txt" End:
#lang debug racket (require memo) (struct Input (polymer insertions) #:transparent) (define (read2 [ip (current-input-port)]) (let loop ([template #f] [insertions (hash)]) (match (read-line ip) [(? eof-object? e) (Input template insertions)] ["" (loop template insertions)] [(regexp "^[A-Z]+$" (list the-template)) (loop the-template insertions)] [(regexp "([A-Z]+) -> ([A-Z]+)" (list _ source dest)) (loop template (hash-set insertions source dest))]))) (define/memoize (step input) #:hash hash (match-define (struct Input (polymer insertions)) input) (define seq (sequence-map string (in-string polymer))) (for/fold ([acc (substring polymer 0 1)] #:result (Input acc insertions)) ([p seq] [q (sequence-tail seq 1)]) (string-append acc (hash-ref insertions (string-append p q) (const "")) q))) (define (histogram seq) (for/fold ([hist (hash)]) ([v seq]) (hash-update hist v add1 (const 0)))) (define (part1_b input) (go input 10)) (define (part1 input) (define final (for/fold ([acc input]) ([n (in-range 1 (add1 10))]) (match-define (and stepped (struct Input (poylmer _))) (step acc)) stepped)) (define hist (histogram (in-string (Input-polymer final)))) (- (argmax identity (hash-values hist)) (argmin identity (hash-values hist)))) (define memo (hash)) (define (go input n) (match-define (struct Input (polymer insertions)) input) (define seq (sequence-map string (in-string polymer))) (define hist (histogram (in-string (for/fold ([s input] #:result (histogram (in-string s))) ([p seq] [q (sequence-tail seq 1)]) (step (Input (string-append p q) insertions)))))) (- (argmax identity (hash-values hist)) (argmin identity (hash-values hist))) ) (define (part2 input) (define final (for/fold ([acc input]) ([n (in-range 1 (add1 40))]) (match-define (and stepped (struct Input (poylmer _))) (step acc)) (printf "Step ~a\n" n) stepped)) (define hist (histogram (in-string (Input-polymer final)))) (- (argmax identity (hash-values hist)) (argmin identity (hash-values hist))) ( go input 40 ) ) (module+ main (define input (read2)) (part1 input) (part2 input))
2f49b55c790335424a6a176f992fbcb70d9b9bd42b4d82a60e26217275cfd6d4
chrovis/cljam
bed.clj
(ns cljam.io.bed "Functions to read and write the BED (Browser Extensible Data) format. See #format1 for the detail BED specifications." (:require [clojure.java.io :as cio] [clojure.string :as cstr] [proton.core :refer [as-long]] [cljam.io.protocols :as protocols] [cljam.util :as util] [cljam.util.chromosome :as chr] [cljam.util.region :as region] [clojure.tools.logging :as logging]) (:import [java.net URL] [java.io BufferedReader BufferedWriter Closeable])) (declare read-fields write-fields) (defrecord BEDReader [^BufferedReader reader ^URL url] Closeable (close [this] (.close ^Closeable (.reader this))) protocols/IReader (reader-url [this] (.url this)) (read [this] (protocols/read this {})) (read [this option] (read-fields this)) (indexed? [_] false) protocols/IRegionReader (read-in-region [this region] (protocols/read-in-region this region {})) (read-in-region [this {:keys [chr start end]} option] (logging/warn "May cause degradation of performance.") (filter (fn [m] (and (or (not chr) (= (:chr m) chr)) (or (not start) (<= start (:start m))) (or (not end) (<= (:end m) end)))) (read-fields this)))) (defrecord BEDWriter [^BufferedWriter writer ^URL url] Closeable (close [this] (.close ^Closeable (.writer this))) protocols/IWriter (writer-url [this] (.url this))) (defn ^BEDReader reader "Returns an open cljam.io.bed.BEDReader of f. Should be used inside with-open to ensure the reader is properly closed." [f] (BEDReader. (cio/reader (util/compressor-input-stream f)) (util/as-url f))) (defn ^BEDWriter writer "Returns an open cljam.io.bed.BEDWriter of f. Should be used inside with-open to ensure the writer is properly closed." [f] (BEDWriter. (cio/writer (util/compressor-output-stream f)) (util/as-url f))) (def ^:const bed-columns [:chr :start :end :name :score :strand :thick-start :thick-end :item-rgb :block-count :block-sizes :block-starts]) (defn- str->long-list "Convert string of comma-separated long values into list of longs. Comma at the end of input string will be ignored. Returns nil if input is nil." [^String s] (when-not (nil? s) (map as-long (cstr/split s #",")))) (defn- long-list->str "Inverse function of str->long-list." [xs] (when (seq xs) (cstr/join "," xs))) (defn- update-some "Same as update if map 'm' contains key 'k'. Otherwise, returns the original map 'm'." [m k f & args] (if (get m k) (apply update m k f args) m)) (defn- deserialize-bed "Parse BED fields string and returns a map. Based on information at #format1." [^String s] First 3 fields are required . (:chr %) (:start %) (:end %) ;; The chromEnd base is not included in the display of the feature. (< (:start %) (:end %)) ;; Lower-numbered fields must be populated if higher-numbered fields are used. (every? true? (drop-while false? (map nil? ((apply juxt bed-columns) %)))) A score between 0 and 1000 . (if-let [s (:score %)] (<= 0 s 1000) true) The number of items in this list should correspond to blockCount . (if-let [xs (:block-sizes %)] (= (count xs) (:block-count %)) true) The number of items in this list should correspond to blockCount . (if-let [xs (:block-starts %)] (= (count xs) (:block-count %)) true) The first blockStart value must be 0 . (if-let [[f] (:block-starts %)] (= 0 f) true) The final blockStart position plus the final blockSize value must equal chromEnd . (if-let [xs (:block-starts %)] (= (+ (last xs) (last (:block-sizes %))) (- (:end %) (:start %))) true) ;; Blocks may not overlap. (if-let [xs (:block-starts %)] (apply <= (mapcat (fn [a b] [a (+ a b)]) xs (:block-sizes %))) true)]} (reduce (fn deserialize-bed-reduce-fn [m [k f]] (update-some m k f)) (zipmap bed-columns (cstr/split s #"\s+")) {:start as-long :end as-long :score as-long :strand #(case % "." nil "+" :forward "-" :reverse) :thick-start as-long :thick-end as-long :block-count as-long :block-sizes str->long-list :block-starts str->long-list})) (defn- serialize-bed "Serialize bed fields into string." [m] First 3 fields are required . (:chr m) (:start m) (:end m) ;; The chromEnd base is not included in the display of the feature. (< (:start m) (:end m)) ;; Lower-numbered fields must be populated if higher-numbered fields are used. (every? true? (drop-while false? (map nil? ((apply juxt bed-columns) m)))) A score between 0 and 1000 . (if-let [s (:score m)] (<= 0 s 1000) true) The number of items in this list should correspond to blockCount . (if-let [xs (:block-sizes m)] (= (count xs) (:block-count m)) true) The number of items in this list should correspond to blockCount . (if-let [xs (:block-starts m)] (= (count xs) (:block-count m)) true) The first blockStart value must be 0 . (if-let [[f] (:block-starts m)] (= 0 f) true) The final blockStart position plus the final blockSize value must equal chromEnd . (if-let [xs (:block-starts m)] (= (+ (last xs) (last (:block-sizes m))) (- (:end m) (:start m))) true) ;; Blocks may not overlap. (if-let [xs (:block-starts m)] (apply <= (mapcat (fn [a b] [a (+ a b)]) xs (:block-sizes m))) true)]} (->> (-> m (update-some :strand #(case % :forward "+" :reverse "-" nil ".")) (update-some :block-sizes long-list->str) (update-some :block-starts long-list->str)) ((apply juxt bed-columns)) (take-while identity) (cstr/join \tab))) (defn- header-or-comment? "Checks if given string is neither a header nor a comment line." [^String s] (or (empty? s) (.startsWith s "browser") (.startsWith s "track") (.startsWith s "#"))) (defn- normalize "Normalize BED fields. BED fields are stored in format: 0-origin and inclusive-start / exclusive-end. This function converts the coordinate into cljam style: 1-origin and inclusive-start / inclusive-end." [m] (-> m (update :start inc) (update-some :thick-start inc))) (defn- denormalize "De-normalize BED fields. This is an inverse function of normalize." [m] (-> m (update :start dec) (update-some :thick-start dec))) (defn read-fields "Returns a lazy sequence of normalized BED fields." [^BEDReader rdr] (sequence (comp (remove header-or-comment?) (map deserialize-bed) (map normalize)) (line-seq (.reader rdr)))) (defn sort-fields "Sort BED fields based on :chr, :start and :end. :chr with common names come first, in order of (chr1, chr2, ..., chrX, chrY, chrM). Other chromosomes follow after in lexicographic order." [xs] (sort-by (fn [m] [(chr/chromosome-order-key (:chr m)) (:start m) (:end m)]) xs)) (defn merge-fields "Sort and merge overlapped regions. Currently, this function affects only :end and :name fields." [xs] (region/merge-regions-with (fn [x {:keys [name end]}] (-> x (update :end max end) (update-some :name str "+" name))) 0 (sort-fields xs))) (defn- fields-<= "Compare two BED fields on the basis of :chr and :end fields." [x y] (<= (compare [(chr/chromosome-order-key (:chr x)) (:end x)] [(chr/chromosome-order-key (:chr y)) (:end y)]) 0)) (defn intersect-fields "Returns a lazy sequence that is the intersection of the two BED sequences. The input sequences will first be sorted with sort-fields, which may cause an extensive memory use for ones with a large number of elements. Note also that this function assumes the input sequences contain only valid regions, and thus :start <= :end holds for each region. Make sure yourself the input sequences meet the condition, or the function may return a wrong result." [xs ys] (letfn [(intersect [xs ys] (lazy-seq (if-let [x (first xs)] (if-let [y (first ys)] (cond->> (if (fields-<= x y) (intersect (next xs) ys) (intersect xs (next ys))) (region/overlapped-regions? x y) (cons (-> x (update :start max (:start y)) (update :end min (:end y))))) []) [])))] (intersect (sort-fields xs) (merge-fields ys)))) (defn subtract-fields "Returns a lazy sequence that is the result of subtracting the BED fields in the sequence ys from the sequence xs. The input sequences will first be sorted with sort-fields, which may cause an extensive memory use for ones with a large number of elements. Note also that this function assumes the input sequences contain only valid regions, and thus :start <= :end holds for each region. Make sure yourself the input sequences meet the condition, or the function may return a wrong result." [xs ys] (letfn [(subtract [xs ys] (lazy-seq (if-let [x (first xs)] (if-let [y (first ys)] (let [[r1 r2] (region/subtract-region x y)] (if r2 (cons r1 (subtract (cons r2 (next xs)) (next ys))) (if r1 (if (fields-<= r1 y) (cons r1 (subtract (next xs) ys)) (subtract (cons r1 (next xs)) (next ys))) (subtract (next xs) ys)))) xs) [])))] (subtract (sort-fields xs) (merge-fields ys)))) (defn complement-fields "Takes a sequence of maps containing :name and :len keys (representing chromosome's name and length, resp.) and a sequence of BED fields, and returns a lazy sequence that is the complement of the BED sequence. The input sequence will first be sorted with sort-fields, which may cause an extensive memory use for ones with a large number of elements. Note also that this function assumes the BED sequence contains only valid regions, and thus :start <= :end holds for each region. Make sure yourself the BED sequence meets the condition, or the function may return a wrong result." [refs xs] (let [chr->len (into {} (map (juxt :name :len)) refs) chrs (sort-by chr/chromosome-order-key (map :name refs))] (when-first [{:keys [chr]} (filter #(not (chr->len (:chr %))) xs)] (let [msg (str "Length of chromosome " chr " not specified")] (throw (IllegalArgumentException. msg)))) (letfn [(complement [xs chrs pos] (lazy-seq (when-let [chr (first chrs)] (let [len (get chr->len chr) x (first xs)] (if (and x (= (:chr x) chr)) (cond->> (complement (next xs) chrs (inc (:end x))) (< pos (:start x)) (cons {:chr chr :start pos :end (dec (:start x))})) (cond->> (complement xs (next chrs) 1) (< pos len) (cons {:chr chr :start pos :end len})))))))] (complement (merge-fields xs) chrs 1)))) (defn write-fields "Write sequence of BED fields to writer." [^BEDWriter wtr xs] (let [w ^BufferedWriter (.writer wtr)] (->> xs (map (comp serialize-bed denormalize)) (cstr/join \newline) (.write w))))
null
https://raw.githubusercontent.com/chrovis/cljam/2b8e7386765be8efdbbbb4f18dbc52447f4a08af/src/cljam/io/bed.clj
clojure
The chromEnd base is not included in the display of the feature. Lower-numbered fields must be populated if higher-numbered fields are used. Blocks may not overlap. The chromEnd base is not included in the display of the feature. Lower-numbered fields must be populated if higher-numbered fields are used. Blocks may not overlap.
(ns cljam.io.bed "Functions to read and write the BED (Browser Extensible Data) format. See #format1 for the detail BED specifications." (:require [clojure.java.io :as cio] [clojure.string :as cstr] [proton.core :refer [as-long]] [cljam.io.protocols :as protocols] [cljam.util :as util] [cljam.util.chromosome :as chr] [cljam.util.region :as region] [clojure.tools.logging :as logging]) (:import [java.net URL] [java.io BufferedReader BufferedWriter Closeable])) (declare read-fields write-fields) (defrecord BEDReader [^BufferedReader reader ^URL url] Closeable (close [this] (.close ^Closeable (.reader this))) protocols/IReader (reader-url [this] (.url this)) (read [this] (protocols/read this {})) (read [this option] (read-fields this)) (indexed? [_] false) protocols/IRegionReader (read-in-region [this region] (protocols/read-in-region this region {})) (read-in-region [this {:keys [chr start end]} option] (logging/warn "May cause degradation of performance.") (filter (fn [m] (and (or (not chr) (= (:chr m) chr)) (or (not start) (<= start (:start m))) (or (not end) (<= (:end m) end)))) (read-fields this)))) (defrecord BEDWriter [^BufferedWriter writer ^URL url] Closeable (close [this] (.close ^Closeable (.writer this))) protocols/IWriter (writer-url [this] (.url this))) (defn ^BEDReader reader "Returns an open cljam.io.bed.BEDReader of f. Should be used inside with-open to ensure the reader is properly closed." [f] (BEDReader. (cio/reader (util/compressor-input-stream f)) (util/as-url f))) (defn ^BEDWriter writer "Returns an open cljam.io.bed.BEDWriter of f. Should be used inside with-open to ensure the writer is properly closed." [f] (BEDWriter. (cio/writer (util/compressor-output-stream f)) (util/as-url f))) (def ^:const bed-columns [:chr :start :end :name :score :strand :thick-start :thick-end :item-rgb :block-count :block-sizes :block-starts]) (defn- str->long-list "Convert string of comma-separated long values into list of longs. Comma at the end of input string will be ignored. Returns nil if input is nil." [^String s] (when-not (nil? s) (map as-long (cstr/split s #",")))) (defn- long-list->str "Inverse function of str->long-list." [xs] (when (seq xs) (cstr/join "," xs))) (defn- update-some "Same as update if map 'm' contains key 'k'. Otherwise, returns the original map 'm'." [m k f & args] (if (get m k) (apply update m k f args) m)) (defn- deserialize-bed "Parse BED fields string and returns a map. Based on information at #format1." [^String s] First 3 fields are required . (:chr %) (:start %) (:end %) (< (:start %) (:end %)) (every? true? (drop-while false? (map nil? ((apply juxt bed-columns) %)))) A score between 0 and 1000 . (if-let [s (:score %)] (<= 0 s 1000) true) The number of items in this list should correspond to blockCount . (if-let [xs (:block-sizes %)] (= (count xs) (:block-count %)) true) The number of items in this list should correspond to blockCount . (if-let [xs (:block-starts %)] (= (count xs) (:block-count %)) true) The first blockStart value must be 0 . (if-let [[f] (:block-starts %)] (= 0 f) true) The final blockStart position plus the final blockSize value must equal chromEnd . (if-let [xs (:block-starts %)] (= (+ (last xs) (last (:block-sizes %))) (- (:end %) (:start %))) true) (if-let [xs (:block-starts %)] (apply <= (mapcat (fn [a b] [a (+ a b)]) xs (:block-sizes %))) true)]} (reduce (fn deserialize-bed-reduce-fn [m [k f]] (update-some m k f)) (zipmap bed-columns (cstr/split s #"\s+")) {:start as-long :end as-long :score as-long :strand #(case % "." nil "+" :forward "-" :reverse) :thick-start as-long :thick-end as-long :block-count as-long :block-sizes str->long-list :block-starts str->long-list})) (defn- serialize-bed "Serialize bed fields into string." [m] First 3 fields are required . (:chr m) (:start m) (:end m) (< (:start m) (:end m)) (every? true? (drop-while false? (map nil? ((apply juxt bed-columns) m)))) A score between 0 and 1000 . (if-let [s (:score m)] (<= 0 s 1000) true) The number of items in this list should correspond to blockCount . (if-let [xs (:block-sizes m)] (= (count xs) (:block-count m)) true) The number of items in this list should correspond to blockCount . (if-let [xs (:block-starts m)] (= (count xs) (:block-count m)) true) The first blockStart value must be 0 . (if-let [[f] (:block-starts m)] (= 0 f) true) The final blockStart position plus the final blockSize value must equal chromEnd . (if-let [xs (:block-starts m)] (= (+ (last xs) (last (:block-sizes m))) (- (:end m) (:start m))) true) (if-let [xs (:block-starts m)] (apply <= (mapcat (fn [a b] [a (+ a b)]) xs (:block-sizes m))) true)]} (->> (-> m (update-some :strand #(case % :forward "+" :reverse "-" nil ".")) (update-some :block-sizes long-list->str) (update-some :block-starts long-list->str)) ((apply juxt bed-columns)) (take-while identity) (cstr/join \tab))) (defn- header-or-comment? "Checks if given string is neither a header nor a comment line." [^String s] (or (empty? s) (.startsWith s "browser") (.startsWith s "track") (.startsWith s "#"))) (defn- normalize "Normalize BED fields. BED fields are stored in format: 0-origin and inclusive-start / exclusive-end. This function converts the coordinate into cljam style: 1-origin and inclusive-start / inclusive-end." [m] (-> m (update :start inc) (update-some :thick-start inc))) (defn- denormalize "De-normalize BED fields. This is an inverse function of normalize." [m] (-> m (update :start dec) (update-some :thick-start dec))) (defn read-fields "Returns a lazy sequence of normalized BED fields." [^BEDReader rdr] (sequence (comp (remove header-or-comment?) (map deserialize-bed) (map normalize)) (line-seq (.reader rdr)))) (defn sort-fields "Sort BED fields based on :chr, :start and :end. :chr with common names come first, in order of (chr1, chr2, ..., chrX, chrY, chrM). Other chromosomes follow after in lexicographic order." [xs] (sort-by (fn [m] [(chr/chromosome-order-key (:chr m)) (:start m) (:end m)]) xs)) (defn merge-fields "Sort and merge overlapped regions. Currently, this function affects only :end and :name fields." [xs] (region/merge-regions-with (fn [x {:keys [name end]}] (-> x (update :end max end) (update-some :name str "+" name))) 0 (sort-fields xs))) (defn- fields-<= "Compare two BED fields on the basis of :chr and :end fields." [x y] (<= (compare [(chr/chromosome-order-key (:chr x)) (:end x)] [(chr/chromosome-order-key (:chr y)) (:end y)]) 0)) (defn intersect-fields "Returns a lazy sequence that is the intersection of the two BED sequences. The input sequences will first be sorted with sort-fields, which may cause an extensive memory use for ones with a large number of elements. Note also that this function assumes the input sequences contain only valid regions, and thus :start <= :end holds for each region. Make sure yourself the input sequences meet the condition, or the function may return a wrong result." [xs ys] (letfn [(intersect [xs ys] (lazy-seq (if-let [x (first xs)] (if-let [y (first ys)] (cond->> (if (fields-<= x y) (intersect (next xs) ys) (intersect xs (next ys))) (region/overlapped-regions? x y) (cons (-> x (update :start max (:start y)) (update :end min (:end y))))) []) [])))] (intersect (sort-fields xs) (merge-fields ys)))) (defn subtract-fields "Returns a lazy sequence that is the result of subtracting the BED fields in the sequence ys from the sequence xs. The input sequences will first be sorted with sort-fields, which may cause an extensive memory use for ones with a large number of elements. Note also that this function assumes the input sequences contain only valid regions, and thus :start <= :end holds for each region. Make sure yourself the input sequences meet the condition, or the function may return a wrong result." [xs ys] (letfn [(subtract [xs ys] (lazy-seq (if-let [x (first xs)] (if-let [y (first ys)] (let [[r1 r2] (region/subtract-region x y)] (if r2 (cons r1 (subtract (cons r2 (next xs)) (next ys))) (if r1 (if (fields-<= r1 y) (cons r1 (subtract (next xs) ys)) (subtract (cons r1 (next xs)) (next ys))) (subtract (next xs) ys)))) xs) [])))] (subtract (sort-fields xs) (merge-fields ys)))) (defn complement-fields "Takes a sequence of maps containing :name and :len keys (representing chromosome's name and length, resp.) and a sequence of BED fields, and returns a lazy sequence that is the complement of the BED sequence. The input sequence will first be sorted with sort-fields, which may cause an extensive memory use for ones with a large number of elements. Note also that this function assumes the BED sequence contains only valid regions, and thus :start <= :end holds for each region. Make sure yourself the BED sequence meets the condition, or the function may return a wrong result." [refs xs] (let [chr->len (into {} (map (juxt :name :len)) refs) chrs (sort-by chr/chromosome-order-key (map :name refs))] (when-first [{:keys [chr]} (filter #(not (chr->len (:chr %))) xs)] (let [msg (str "Length of chromosome " chr " not specified")] (throw (IllegalArgumentException. msg)))) (letfn [(complement [xs chrs pos] (lazy-seq (when-let [chr (first chrs)] (let [len (get chr->len chr) x (first xs)] (if (and x (= (:chr x) chr)) (cond->> (complement (next xs) chrs (inc (:end x))) (< pos (:start x)) (cons {:chr chr :start pos :end (dec (:start x))})) (cond->> (complement xs (next chrs) 1) (< pos len) (cons {:chr chr :start pos :end len})))))))] (complement (merge-fields xs) chrs 1)))) (defn write-fields "Write sequence of BED fields to writer." [^BEDWriter wtr xs] (let [w ^BufferedWriter (.writer wtr)] (->> xs (map (comp serialize-bed denormalize)) (cstr/join \newline) (.write w))))
277411c78a1bbea173e861d2cf64c26acabf1cdccd45c9a2197e85ccb7fb97e7
mikeball/foundation
reading.clj
(ns taoclj.foundation.reading (:require [taoclj.foundation.naming :refer [from-db-name]] [cheshire.core :as cheshire]) (:import [java.sql Types])) ; *** result set readers ********************* ; array conversions (def type-int-array (Class/forName "[I")) (def type-string-array (Class/forName "[Ljava.lang.String;")) ; left off need to add support for all array types ; also get type only once, use let block (defn is-array? [item] (or (= type-string-array (type item)))) (defn convert-array [array] (let [top-level-list (seq (.getArray array))] ; top-level-list (map (fn [item] (if (is-array? item) (seq item) ; convert sub-arrays item)) top-level-list) )) (defn convert-from-db [rsmeta result-set index] (let [ct (.getColumnType rsmeta index) ctn (.getColumnTypeName rsmeta index)] (cond (= ct Types/TIMESTAMP) (if-let [ts (.getTimestamp result-set index)] (.toInstant ts)) (= ct Types/ARRAY) (if-let [a (.getArray result-set index)] (convert-array a)) (= ctn "json") (if-let [json (.getObject result-set index)] (cheshire/parse-string json (fn [k] (keyword k)))) :default (.getObject result-set index)))) (defn read-resultset ([^java.sql.ResultSet rs] (read-resultset rs nil)) ([^java.sql.ResultSet rs result-format] (let [rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) columns (map from-db-name (map #(.getColumnLabel rsmeta %) idxs) ) dups (or (apply distinct? columns) (throw (Exception. "ResultSet must have unique column names"))) ; break out function for perf get-row-vals (fn [] (map (fn [^Integer i] (convert-from-db rsmeta rs i)) idxs)) ; break out function for perf read-rows (fn readrow [] (when (.next rs) (if (= result-format :rows) (cons (vec (get-row-vals)) (readrow)) (cons (zipmap columns (get-row-vals)) (readrow)))))] (if (= result-format :rows) (cons (vec columns) (read-rows)) (read-rows)) ))) (defn read-resultsets [^java.sql.Statement statement result-format] (let [read-sets (fn readrs [] (let [rs (.getResultSet statement)] (cons (read-resultset rs result-format) (if (.getMoreResults statement) (readrs))))) results (read-sets)] (if (= 1 (count results)) (first results) results )))
null
https://raw.githubusercontent.com/mikeball/foundation/a0376f49759b1552f2f70e7585029b592b6fb346/src/taoclj/foundation/reading.clj
clojure
*** result set readers ********************* array conversions left off need to add support for all array types also get type only once, use let block top-level-list convert sub-arrays break out function for perf break out function for perf
(ns taoclj.foundation.reading (:require [taoclj.foundation.naming :refer [from-db-name]] [cheshire.core :as cheshire]) (:import [java.sql Types])) (def type-int-array (Class/forName "[I")) (def type-string-array (Class/forName "[Ljava.lang.String;")) (defn is-array? [item] (or (= type-string-array (type item)))) (defn convert-array [array] (let [top-level-list (seq (.getArray array))] (map (fn [item] (if (is-array? item) item)) top-level-list) )) (defn convert-from-db [rsmeta result-set index] (let [ct (.getColumnType rsmeta index) ctn (.getColumnTypeName rsmeta index)] (cond (= ct Types/TIMESTAMP) (if-let [ts (.getTimestamp result-set index)] (.toInstant ts)) (= ct Types/ARRAY) (if-let [a (.getArray result-set index)] (convert-array a)) (= ctn "json") (if-let [json (.getObject result-set index)] (cheshire/parse-string json (fn [k] (keyword k)))) :default (.getObject result-set index)))) (defn read-resultset ([^java.sql.ResultSet rs] (read-resultset rs nil)) ([^java.sql.ResultSet rs result-format] (let [rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) columns (map from-db-name (map #(.getColumnLabel rsmeta %) idxs) ) dups (or (apply distinct? columns) (throw (Exception. "ResultSet must have unique column names"))) get-row-vals (fn [] (map (fn [^Integer i] (convert-from-db rsmeta rs i)) idxs)) read-rows (fn readrow [] (when (.next rs) (if (= result-format :rows) (cons (vec (get-row-vals)) (readrow)) (cons (zipmap columns (get-row-vals)) (readrow)))))] (if (= result-format :rows) (cons (vec columns) (read-rows)) (read-rows)) ))) (defn read-resultsets [^java.sql.Statement statement result-format] (let [read-sets (fn readrs [] (let [rs (.getResultSet statement)] (cons (read-resultset rs result-format) (if (.getMoreResults statement) (readrs))))) results (read-sets)] (if (= 1 (count results)) (first results) results )))
6209d5bac836b73db39973917dcef859bfafed94a7dfc566d8f94be1d306e4a9
emotiq/emotiq
socket-actors-test.lisp
;;; socket-actor-test.lisp ;;; Tests of actor sockets, without gossip (ql:quickload :gossip) (in-package :gossip) (defparameter *server-address* "localhost") ;(defparameter *server-address* "ec2-35-157-133-208.eu-central-1.compute.amazonaws.com") (defun setup-server () ; Start listener socket thread (start-gossip-server :TCP)) (defparameter *stop-loopback* nil) (defun loopback-server () "Wait for an object to appear -- from anywhere -- and echo it." (setup-server) (setf *stop-loopback* nil) (loop until *stop-loopback* do (multiple-value-bind (object valid) (mpcompat:mailbox-read *incoming-mailbox* 10) (when valid (destructuring-bind (reply-actor msg) object (ac:send reply-actor :send-socket-data (concatenate 'string msg "GOO"))))))) ; (trace ac:send) ; (loopback-server) (defun setup-client () ; Start listener socket thread (start-gossip-server :TCP)) (defun test-sa-client1 (&optional server-address) "Assumes (loopback-server) is running on server" (archive-log) (setup-client) (unless server-address (setf server-address *server-address*)) (let* ((server-port (if (equalp "localhost" server-address) (other-tcp-port) *nominal-gossip-port*)) (mbox nil)) (multiple-value-bind (socket-actor errorp) (ensure-connection server-address server-port) (cond ((null errorp) (setf mbox (get-outbox socket-actor)) (ac:send socket-actor :send-socket-data "Foo") (mpcompat:mailbox-read mbox 10)) (t (error errorp)))))) ; (test-sa-client1) ; should return (<some actor> "FooGOO") ; (test-sa-client1 "ec2-35-157-133-208.eu-central-1.compute.amazonaws.com") ; (test-sa-client1 "emq-01.aws.emotiq.ch")
null
https://raw.githubusercontent.com/emotiq/emotiq/9af78023f670777895a3dac29a2bbe98e19b6249/src/gossip/attic/socket-actors-test.lisp
lisp
socket-actor-test.lisp Tests of actor sockets, without gossip (defparameter *server-address* "ec2-35-157-133-208.eu-central-1.compute.amazonaws.com") Start listener socket thread (trace ac:send) (loopback-server) Start listener socket thread (test-sa-client1) ; should return (<some actor> "FooGOO") (test-sa-client1 "ec2-35-157-133-208.eu-central-1.compute.amazonaws.com") (test-sa-client1 "emq-01.aws.emotiq.ch")
(ql:quickload :gossip) (in-package :gossip) (defparameter *server-address* "localhost") (defun setup-server () (start-gossip-server :TCP)) (defparameter *stop-loopback* nil) (defun loopback-server () "Wait for an object to appear -- from anywhere -- and echo it." (setup-server) (setf *stop-loopback* nil) (loop until *stop-loopback* do (multiple-value-bind (object valid) (mpcompat:mailbox-read *incoming-mailbox* 10) (when valid (destructuring-bind (reply-actor msg) object (ac:send reply-actor :send-socket-data (concatenate 'string msg "GOO"))))))) (defun setup-client () (start-gossip-server :TCP)) (defun test-sa-client1 (&optional server-address) "Assumes (loopback-server) is running on server" (archive-log) (setup-client) (unless server-address (setf server-address *server-address*)) (let* ((server-port (if (equalp "localhost" server-address) (other-tcp-port) *nominal-gossip-port*)) (mbox nil)) (multiple-value-bind (socket-actor errorp) (ensure-connection server-address server-port) (cond ((null errorp) (setf mbox (get-outbox socket-actor)) (ac:send socket-actor :send-socket-data "Foo") (mpcompat:mailbox-read mbox 10)) (t (error errorp))))))
8a57a9f71587acf51580e160eb4a47e10f367ea140aa44637b2189dfdf0e3960
jbclements/sxml
ssax.rkt
#lang racket/base (require "myenv.rkt") (require "util.rkt") (require "parse-error.rkt") (require "input-parse.rkt") (require "SSAX-code.rkt") (require "SXML-tree-trans.rkt") (require "sxpathlib.rkt") (require "access-remote.rkt") (require "id.rkt") (require "xlink-parser.rkt") (require "ssax-prim.rkt") (require "multi-parser.rkt") (provide (all-from-out "myenv.rkt")) (provide (all-from-out "util.rkt")) (provide (all-from-out "parse-error.rkt")) (provide (all-from-out "input-parse.rkt")) (provide (all-from-out "SSAX-code.rkt")) (provide (all-from-out "SXML-tree-trans.rkt")) (provide (all-from-out "sxpathlib.rkt")) (provide (all-from-out "access-remote.rkt")) (provide (all-from-out "id.rkt")) (provide (all-from-out "xlink-parser.rkt")) (provide (all-from-out "ssax-prim.rkt")) (provide (all-from-out "multi-parser.rkt"))
null
https://raw.githubusercontent.com/jbclements/sxml/d3b8570cf7287c4e06636e17634f0f5c39203d52/sxml/ssax/ssax.rkt
racket
#lang racket/base (require "myenv.rkt") (require "util.rkt") (require "parse-error.rkt") (require "input-parse.rkt") (require "SSAX-code.rkt") (require "SXML-tree-trans.rkt") (require "sxpathlib.rkt") (require "access-remote.rkt") (require "id.rkt") (require "xlink-parser.rkt") (require "ssax-prim.rkt") (require "multi-parser.rkt") (provide (all-from-out "myenv.rkt")) (provide (all-from-out "util.rkt")) (provide (all-from-out "parse-error.rkt")) (provide (all-from-out "input-parse.rkt")) (provide (all-from-out "SSAX-code.rkt")) (provide (all-from-out "SXML-tree-trans.rkt")) (provide (all-from-out "sxpathlib.rkt")) (provide (all-from-out "access-remote.rkt")) (provide (all-from-out "id.rkt")) (provide (all-from-out "xlink-parser.rkt")) (provide (all-from-out "ssax-prim.rkt")) (provide (all-from-out "multi-parser.rkt"))
e6b3d9ee86e8199892e2c9a5f29816f2a387b7fa4068b4cbcc309c378254802f
richhickey/rdfm
rdfm.clj
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns org.clojure.rdfm (:refer-clojure :exclude [assoc dissoc]) (:import (java.util UUID) (javax.xml.datatype DatatypeFactory XMLGregorianCalendar) (org.openrdf.repository Repository RepositoryConnection) (org.openrdf.model Literal Resource Statement URI Value ValueFactory))) (alias 'core 'clojure.core) (set! *warn-on-reflection* true) (set! *print-meta* false) ;todo - make these private (def #^"[Lorg.openrdf.model.Resource;" NOCONTEXT (make-array org.openrdf.model.Resource 0)) (def DATA-NS "/") (def SCALAR-NS (str DATA-NS "scalar/")) (def KEYWORD-NS (str SCALAR-NS "keyword/")) (def COLL-NS (str DATA-NS "collection/")) (def VEC-NS (str COLL-NS "vector#")) (def MAP-NS (str COLL-NS "hash-map#")) (def #^String RDF-NS "-rdf-syntax-ns#") (def #^String RDF-NUMBER-NS "-rdf-syntax-ns#_") (def UUID-NS "urn:uuid:") (def #^RepositoryConnection *conn*) (def #^ValueFactory *vf*) (defmacro dotrans [conn & body] `(let [conn# ~conn] (binding [*conn* conn# *vf* (.getValueFactory #^RepositoryConnection conn#)] (try (let [ret# (do ~@body)] (.commit *conn*) ret#) (catch Exception e# (.rollback *conn*) (throw e#)))))) (defn idof [x] (::id (meta x))) (defn- kw->uri [k] (.createURI *vf* KEYWORD-NS (subs (str k) 1))) (defn- uri->kw [uri] (keyword (subs (str uri) (count KEYWORD-NS)))) (defn random-uuid-uri [prefix] (java.net.URI. (str prefix (java.util.UUID/randomUUID)))) (declare store-1) (defn- resource-for [id] (condp instance? id Resource id java.net.URI (.createURI *vf* (str id)) String (.createURI *vf* id))) (defn- value-for [o] (condp instance? o clojure.lang.IPersistentCollection (do (assert (idof o)) (resource-for (idof o))) Value o String (.createLiteral *vf* #^String o) Integer (.createLiteral *vf* (int o)) Long (.createLiteral *vf* (long o)) Float (.createLiteral *vf* (float o)) Double (.createLiteral *vf* (double o)) Boolean (.createLiteral *vf* (boolean o)) java.net.URI (.createURI *vf* (str o)) clojure.lang.Keyword (kw->uri o) BigInteger (.createLiteral *vf* (str o) (.createURI *vf* "#integer")) BigDecimal (.createLiteral *vf* (str o) (.createURI *vf* "#decimal")) XMLGregorianCalendar (.createLiteral *vf* #^XMLGregorianCalendar o))) (def value-extractors {"" #(.getLabel #^Literal %) "#int" #(.intValue #^Literal %) "#long" #(.longValue #^Literal %) "#float" #(.floatValue #^Literal %) "#double" #(.doubleValue #^Literal %) "#boolean" #(.booleanValue #^Literal %) "#integer" #(.integerValue #^Literal %) "#decimal" #(.decimalValue #^Literal %) "#dateTime" #(.calendarValue #^Literal %) "#time" #(.calendarValue #^Literal %) "#date" #(.calendarValue #^Literal %) "#gYearMonth" #(.calendarValue #^Literal %) "#gMonthDay" #(.calendarValue #^Literal %) "#gYear" #(.calendarValue #^Literal %) "#gMonth" #(.calendarValue #^Literal %) "#gDay" #(.calendarValue #^Literal %)}) (defn- extract-value [v] (condp instance? v URI (if (.startsWith (str v) KEYWORD-NS) (uri->kw v) v) Literal ((value-extractors (str (.getDatatype #^Literal v))) v))) (defn- property-uri [k] (cond (string? k) (.createURI *vf* k) (keyword? k) (kw->uri k) (integer? k) (.createURI *vf* RDF-NS (str "_" (inc k))) :else (throw (IllegalArgumentException. (str "Unsupported key type: " (class k)))))) (defn- property-key [p] (let [id (str p)] (cond (.startsWith id KEYWORD-NS) (uri->kw p) (.startsWith id RDF-NUMBER-NS) (dec (-> id (subs 44) Integer/parseInt)) :else id))) (defn- add-statement [s p o] (.add *conn* (.createStatement *vf* s p o) NOCONTEXT)) (defmulti store-initial (fn [o & id] (class o))) (defn store-meta [o] (let [ret-meta (core/dissoc (meta o) ::id)] (if (pos? (count ret-meta)) (let [m (store-initial ret-meta (random-uuid-uri UUID-NS))] (add-statement (resource-for (idof o)) (property-uri ::meta) (resource-for (idof m))) (with-meta o (core/assoc m ::id (idof o)))) o))) (defmethod store-initial :default [x & id] x) (defmethod store-initial clojure.lang.IPersistentVector [vec] (if (idof vec) vec (let [id (random-uuid-uri VEC-NS) res (resource-for id) ret (reduce (fn [vret i] (let [v (store-initial (vec i))] (add-statement res (property-uri i) (value-for v)) (conj vret v))) [] (range (count vec))) ret ( with - meta ret ( assoc ( ) : : i d i d ) ) ret ( store - meta ret ) ret (with-meta ret {::id id})] ret))) (defn store-map-val [m k v] (let [res (resource-for (idof m)) store1 (fn [v] (let [nested (store-initial v)] (add-statement res (property-uri k) (value-for nested)) nested))] (cond (set? v) (core/assoc m k (reduce (fn [s v] (conj s (store1 v))) #{} v)) :else (core/assoc m k (store1 v))))) (defmethod store-initial clojure.lang.IPersistentMap ([m] (if (idof m) m (store-initial m (random-uuid-uri MAP-NS)))) ([m id] (let [res (resource-for id) ret (reduce (fn [mret [k v]] (letfn [(store1 [v] (let [nested (store-initial v)] (add-statement res (property-uri k) (value-for nested)) nested))] (cond (set? v) (core/assoc mret k (reduce (fn [s v] (conj s (store1 v))) #{} v)) :else (core/assoc mret k (store1 v))))) {} m) ret (with-meta ret (core/assoc (meta m) ::id id)) ret (store-meta ret)] ret))) (defn store-root ([m] (store-root m (random-uuid-uri UUID-NS))) ([m uri] (store-initial m uri))) (defn get-statements [id] (let [res (.getStatements *conn* (resource-for id) nil nil false NOCONTEXT) ret (into [] (.asList res))] (.close res) ret)) (defn remove-all [id] (.remove *conn* (resource-for id) nil nil NOCONTEXT)) (declare pull) (defn restore-value [value] (let [v (extract-value value)] (if (instance? URI v) (let [id (str v)] (cond (.startsWith id COLL-NS) (pull id) :else (java.net.URI. (str v)))) v))) (defn setify [x] (if (set? x) x #{x})) (defn uri->id [uri] (condp instance? uri String uri java.net.URI uri URI (java.net.URI. (str uri)))) (defn pull [id] (let [statements (get-statements id) id-str (str id)] (cond (.startsWith id-str VEC-NS) (with-meta (reduce (fn [v #^Statement s] (let [p (property-key (.getPredicate s)) o (.getObject s)] (core/assoc v p (restore-value o)))) (vec (repeat (count statements) nil)) statements) {::id id-str}) :else (vary-meta (reduce (fn [m #^Statement s] (let [k (property-key (.getPredicate s)) v (restore-value (.getObject s))] (cond (= k ::meta) (with-meta m v) (contains? m k) (core/assoc m k (conj (setify (m k)) v)) :else (core/assoc m k v)))) {} statements) core/assoc ::id (uri->id id))))) (defn store-vec-val [vec k v] (let [res (resource-for (idof vec)) val (store-initial v)] (add-statement res (property-uri k) (value-for val)) (core/assoc vec k val))) (defn assoc [idcoll k v] (if (vector? idcoll) (store-vec-val idcoll k v) (let [m (if (map? idcoll) idcoll (with-meta {} {::id idcoll}))] (.remove *conn* (resource-for (idof m)) (property-uri k) nil NOCONTEXT) (store-map-val m k v)))) (defn assoc* [idcoll k v] (let [m (if (map? idcoll) idcoll (with-meta {} {::id idcoll}))] (if (set? v) (reduce #(assoc* %1 k %2) m v) (let [res (resource-for (idof m)) val (store-initial v)] (add-statement res (property-uri k) (value-for val)) (core/assoc m k (conj (setify (get m k #{})) val)))))) (defn dissoc [idm k] (let [id (if (map? idm) (idof idm) idm)] (.remove *conn* (resource-for id) (property-uri k) nil NOCONTEXT) (when (map? idm) (core/dissoc idm k)))) (defn dissoc* [idm k v] (if (set? v) (reduce #(dissoc* %1 k %2) idm v) (let [id (if (map? idm) (idof idm) idm)] (.remove *conn* (resource-for id) (property-uri k) (value-for v) NOCONTEXT) (if (and (map? idm) (contains? idm k)) (let [vs (idm k)] (cond (set? vs) (let [vs- (disj vs v)] (if (not-empty vs-) (core/assoc idm k vs-) (core/dissoc idm k))) (= vs v) (core/dissoc idm k) :else idm)) idm)))) (comment ;fiddle (import (org.openrdf.repository Repository RepositoryConnection) (org.openrdf.repository.sail SailRepository) (org.openrdf.repository.http HTTPRepository) (org.openrdf.sail.memory MemoryStore)) (alias 'rdfm 'org.clojure.rdfm) (def #^Repository repo (SailRepository. (MemoryStore. (java.io.File. "/Users/rich/dev/data/db")))) (.initialize repo) (def c (.getConnection repo)) (def x (rdfm/dotrans c (rdfm/store-root {:a 1 :b 2 :c [3 4 [5 6 {:seven :eight}]] :d "six" :e {:f 7 :g #{8}}}))) (def xs (rdfm/dotrans c (rdfm/pull (::org.clojure.rdfm/id (meta x))))) (def xss (rdfm/dotrans c (rdfm/assoc xs :a :42))) (def xfb (rdfm/dotrans c (update-in xss [:e] rdfm/assoc :foo :bar))) (def xc42 (rdfm/dotrans c (update-in xfb [:c] rdfm/assoc 0 42))) (def xg42 (rdfm/dotrans c (update-in xc42 [:e] rdfm/assoc* :g #{43 44}))) (def x-b (rdfm/dotrans c (rdfm/dissoc xg42 :b))) (def xg44 (rdfm/dotrans c (update-in x-b [:e] rdfm/dissoc* :g 43))) (.close c) (.shutDown repo) cruft needed for dates import java.util . GregorianCalendar ; import javax.xml.datatype . DatatypeFactory ; import javax.xml.datatype . XMLGregorianCalendar GregorianCalendar c = new GregorianCalendar ( ) ; ;c.setTime(yourDate); = DatatypeFactory.newInstance().newXMLGregorianCalendar(c ) ; ( def # ^DatatypeFactory dtf ( DatatypeFactory / newInstance ) ) )
null
https://raw.githubusercontent.com/richhickey/rdfm/d3adeb5f0eb9438d52cc5d1008c3b6163f3a2bc1/src/org/clojure/rdfm.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. todo - make these private fiddle c.setTime(yourDate);
Copyright ( c ) . All rights reserved . (ns org.clojure.rdfm (:refer-clojure :exclude [assoc dissoc]) (:import (java.util UUID) (javax.xml.datatype DatatypeFactory XMLGregorianCalendar) (org.openrdf.repository Repository RepositoryConnection) (org.openrdf.model Literal Resource Statement URI Value ValueFactory))) (alias 'core 'clojure.core) (set! *warn-on-reflection* true) (set! *print-meta* false) (def #^"[Lorg.openrdf.model.Resource;" NOCONTEXT (make-array org.openrdf.model.Resource 0)) (def DATA-NS "/") (def SCALAR-NS (str DATA-NS "scalar/")) (def KEYWORD-NS (str SCALAR-NS "keyword/")) (def COLL-NS (str DATA-NS "collection/")) (def VEC-NS (str COLL-NS "vector#")) (def MAP-NS (str COLL-NS "hash-map#")) (def #^String RDF-NS "-rdf-syntax-ns#") (def #^String RDF-NUMBER-NS "-rdf-syntax-ns#_") (def UUID-NS "urn:uuid:") (def #^RepositoryConnection *conn*) (def #^ValueFactory *vf*) (defmacro dotrans [conn & body] `(let [conn# ~conn] (binding [*conn* conn# *vf* (.getValueFactory #^RepositoryConnection conn#)] (try (let [ret# (do ~@body)] (.commit *conn*) ret#) (catch Exception e# (.rollback *conn*) (throw e#)))))) (defn idof [x] (::id (meta x))) (defn- kw->uri [k] (.createURI *vf* KEYWORD-NS (subs (str k) 1))) (defn- uri->kw [uri] (keyword (subs (str uri) (count KEYWORD-NS)))) (defn random-uuid-uri [prefix] (java.net.URI. (str prefix (java.util.UUID/randomUUID)))) (declare store-1) (defn- resource-for [id] (condp instance? id Resource id java.net.URI (.createURI *vf* (str id)) String (.createURI *vf* id))) (defn- value-for [o] (condp instance? o clojure.lang.IPersistentCollection (do (assert (idof o)) (resource-for (idof o))) Value o String (.createLiteral *vf* #^String o) Integer (.createLiteral *vf* (int o)) Long (.createLiteral *vf* (long o)) Float (.createLiteral *vf* (float o)) Double (.createLiteral *vf* (double o)) Boolean (.createLiteral *vf* (boolean o)) java.net.URI (.createURI *vf* (str o)) clojure.lang.Keyword (kw->uri o) BigInteger (.createLiteral *vf* (str o) (.createURI *vf* "#integer")) BigDecimal (.createLiteral *vf* (str o) (.createURI *vf* "#decimal")) XMLGregorianCalendar (.createLiteral *vf* #^XMLGregorianCalendar o))) (def value-extractors {"" #(.getLabel #^Literal %) "#int" #(.intValue #^Literal %) "#long" #(.longValue #^Literal %) "#float" #(.floatValue #^Literal %) "#double" #(.doubleValue #^Literal %) "#boolean" #(.booleanValue #^Literal %) "#integer" #(.integerValue #^Literal %) "#decimal" #(.decimalValue #^Literal %) "#dateTime" #(.calendarValue #^Literal %) "#time" #(.calendarValue #^Literal %) "#date" #(.calendarValue #^Literal %) "#gYearMonth" #(.calendarValue #^Literal %) "#gMonthDay" #(.calendarValue #^Literal %) "#gYear" #(.calendarValue #^Literal %) "#gMonth" #(.calendarValue #^Literal %) "#gDay" #(.calendarValue #^Literal %)}) (defn- extract-value [v] (condp instance? v URI (if (.startsWith (str v) KEYWORD-NS) (uri->kw v) v) Literal ((value-extractors (str (.getDatatype #^Literal v))) v))) (defn- property-uri [k] (cond (string? k) (.createURI *vf* k) (keyword? k) (kw->uri k) (integer? k) (.createURI *vf* RDF-NS (str "_" (inc k))) :else (throw (IllegalArgumentException. (str "Unsupported key type: " (class k)))))) (defn- property-key [p] (let [id (str p)] (cond (.startsWith id KEYWORD-NS) (uri->kw p) (.startsWith id RDF-NUMBER-NS) (dec (-> id (subs 44) Integer/parseInt)) :else id))) (defn- add-statement [s p o] (.add *conn* (.createStatement *vf* s p o) NOCONTEXT)) (defmulti store-initial (fn [o & id] (class o))) (defn store-meta [o] (let [ret-meta (core/dissoc (meta o) ::id)] (if (pos? (count ret-meta)) (let [m (store-initial ret-meta (random-uuid-uri UUID-NS))] (add-statement (resource-for (idof o)) (property-uri ::meta) (resource-for (idof m))) (with-meta o (core/assoc m ::id (idof o)))) o))) (defmethod store-initial :default [x & id] x) (defmethod store-initial clojure.lang.IPersistentVector [vec] (if (idof vec) vec (let [id (random-uuid-uri VEC-NS) res (resource-for id) ret (reduce (fn [vret i] (let [v (store-initial (vec i))] (add-statement res (property-uri i) (value-for v)) (conj vret v))) [] (range (count vec))) ret ( with - meta ret ( assoc ( ) : : i d i d ) ) ret ( store - meta ret ) ret (with-meta ret {::id id})] ret))) (defn store-map-val [m k v] (let [res (resource-for (idof m)) store1 (fn [v] (let [nested (store-initial v)] (add-statement res (property-uri k) (value-for nested)) nested))] (cond (set? v) (core/assoc m k (reduce (fn [s v] (conj s (store1 v))) #{} v)) :else (core/assoc m k (store1 v))))) (defmethod store-initial clojure.lang.IPersistentMap ([m] (if (idof m) m (store-initial m (random-uuid-uri MAP-NS)))) ([m id] (let [res (resource-for id) ret (reduce (fn [mret [k v]] (letfn [(store1 [v] (let [nested (store-initial v)] (add-statement res (property-uri k) (value-for nested)) nested))] (cond (set? v) (core/assoc mret k (reduce (fn [s v] (conj s (store1 v))) #{} v)) :else (core/assoc mret k (store1 v))))) {} m) ret (with-meta ret (core/assoc (meta m) ::id id)) ret (store-meta ret)] ret))) (defn store-root ([m] (store-root m (random-uuid-uri UUID-NS))) ([m uri] (store-initial m uri))) (defn get-statements [id] (let [res (.getStatements *conn* (resource-for id) nil nil false NOCONTEXT) ret (into [] (.asList res))] (.close res) ret)) (defn remove-all [id] (.remove *conn* (resource-for id) nil nil NOCONTEXT)) (declare pull) (defn restore-value [value] (let [v (extract-value value)] (if (instance? URI v) (let [id (str v)] (cond (.startsWith id COLL-NS) (pull id) :else (java.net.URI. (str v)))) v))) (defn setify [x] (if (set? x) x #{x})) (defn uri->id [uri] (condp instance? uri String uri java.net.URI uri URI (java.net.URI. (str uri)))) (defn pull [id] (let [statements (get-statements id) id-str (str id)] (cond (.startsWith id-str VEC-NS) (with-meta (reduce (fn [v #^Statement s] (let [p (property-key (.getPredicate s)) o (.getObject s)] (core/assoc v p (restore-value o)))) (vec (repeat (count statements) nil)) statements) {::id id-str}) :else (vary-meta (reduce (fn [m #^Statement s] (let [k (property-key (.getPredicate s)) v (restore-value (.getObject s))] (cond (= k ::meta) (with-meta m v) (contains? m k) (core/assoc m k (conj (setify (m k)) v)) :else (core/assoc m k v)))) {} statements) core/assoc ::id (uri->id id))))) (defn store-vec-val [vec k v] (let [res (resource-for (idof vec)) val (store-initial v)] (add-statement res (property-uri k) (value-for val)) (core/assoc vec k val))) (defn assoc [idcoll k v] (if (vector? idcoll) (store-vec-val idcoll k v) (let [m (if (map? idcoll) idcoll (with-meta {} {::id idcoll}))] (.remove *conn* (resource-for (idof m)) (property-uri k) nil NOCONTEXT) (store-map-val m k v)))) (defn assoc* [idcoll k v] (let [m (if (map? idcoll) idcoll (with-meta {} {::id idcoll}))] (if (set? v) (reduce #(assoc* %1 k %2) m v) (let [res (resource-for (idof m)) val (store-initial v)] (add-statement res (property-uri k) (value-for val)) (core/assoc m k (conj (setify (get m k #{})) val)))))) (defn dissoc [idm k] (let [id (if (map? idm) (idof idm) idm)] (.remove *conn* (resource-for id) (property-uri k) nil NOCONTEXT) (when (map? idm) (core/dissoc idm k)))) (defn dissoc* [idm k v] (if (set? v) (reduce #(dissoc* %1 k %2) idm v) (let [id (if (map? idm) (idof idm) idm)] (.remove *conn* (resource-for id) (property-uri k) (value-for v) NOCONTEXT) (if (and (map? idm) (contains? idm k)) (let [vs (idm k)] (cond (set? vs) (let [vs- (disj vs v)] (if (not-empty vs-) (core/assoc idm k vs-) (core/dissoc idm k))) (= vs v) (core/dissoc idm k) :else idm)) idm)))) (comment (import (org.openrdf.repository Repository RepositoryConnection) (org.openrdf.repository.sail SailRepository) (org.openrdf.repository.http HTTPRepository) (org.openrdf.sail.memory MemoryStore)) (alias 'rdfm 'org.clojure.rdfm) (def #^Repository repo (SailRepository. (MemoryStore. (java.io.File. "/Users/rich/dev/data/db")))) (.initialize repo) (def c (.getConnection repo)) (def x (rdfm/dotrans c (rdfm/store-root {:a 1 :b 2 :c [3 4 [5 6 {:seven :eight}]] :d "six" :e {:f 7 :g #{8}}}))) (def xs (rdfm/dotrans c (rdfm/pull (::org.clojure.rdfm/id (meta x))))) (def xss (rdfm/dotrans c (rdfm/assoc xs :a :42))) (def xfb (rdfm/dotrans c (update-in xss [:e] rdfm/assoc :foo :bar))) (def xc42 (rdfm/dotrans c (update-in xfb [:c] rdfm/assoc 0 42))) (def xg42 (rdfm/dotrans c (update-in xc42 [:e] rdfm/assoc* :g #{43 44}))) (def x-b (rdfm/dotrans c (rdfm/dissoc xg42 :b))) (def xg44 (rdfm/dotrans c (update-in x-b [:e] rdfm/dissoc* :g 43))) (.close c) (.shutDown repo) cruft needed for dates import javax.xml.datatype . XMLGregorianCalendar ( def # ^DatatypeFactory dtf ( DatatypeFactory / newInstance ) ) )
d67a41e1d4710693fa0d76c9bdeedb629d3111a110d404ac1847bfda7b434c5f
input-output-hk/ouroboros-network
LeaderSchedule.hs
{-# LANGUAGE NamedFieldPuns #-} # LANGUAGE RecordWildCards # # LANGUAGE TypeApplications # module Test.ThreadNet.LeaderSchedule (tests) where import Control.Monad (replicateM) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Test.QuickCheck import Test.Tasty import Test.Tasty.QuickCheck import Ouroboros.Consensus.Block import Ouroboros.Consensus.BlockchainTime import Ouroboros.Consensus.Config.SecurityParam import qualified Ouroboros.Consensus.HardFork.History as HardFork import Ouroboros.Consensus.Mock.Ledger import Ouroboros.Consensus.Mock.Node () import Ouroboros.Consensus.Mock.Node.PraosRule import Ouroboros.Consensus.Mock.Protocol.LeaderSchedule import Ouroboros.Consensus.Mock.Protocol.Praos import Ouroboros.Consensus.Node.ProtocolInfo import Ouroboros.Consensus.NodeId import Test.ThreadNet.General import Test.ThreadNet.TxGen.Mock () import Test.ThreadNet.Util import Test.ThreadNet.Util.HasCreator.Mock () import Test.ThreadNet.Util.NodeJoinPlan import Test.ThreadNet.Util.NodeRestarts import Test.ThreadNet.Util.NodeToNodeVersion import Test.ThreadNet.Util.SimpleBlock import Test.Util.HardFork.Future (singleEraFuture) import Test.Util.Orphans.Arbitrary () import Test.Util.Slots (NumSlots (..)) data TestSetup = TestSetup { setupK :: SecurityParam , setupTestConfig :: TestConfig , setupEpochSize :: EpochSize -- ^ Note: we don't think this value actually matters, since this test -- overrides the leader schedule. , setupNodeJoinPlan :: NodeJoinPlan , setupLeaderSchedule :: LeaderSchedule , setupSlotLength :: SlotLength } deriving (Show) instance Arbitrary TestSetup where arbitrary = do TODO k > 1 as a workaround for Issue # 1511 . k <- SecurityParam <$> choose (2, 10) epochSize <- EpochSize <$> choose (1, 10) slotLength <- arbitrary testConfig <- arbitrary let TestConfig{numCoreNodes, numSlots} = testConfig nodeJoinPlan <- genNodeJoinPlan numCoreNodes numSlots leaderSchedule <- genLeaderSchedule k numSlots numCoreNodes nodeJoinPlan pure $ TestSetup k testConfig epochSize nodeJoinPlan leaderSchedule slotLength -- TODO shrink tests :: TestTree tests = testGroup "LeaderSchedule" [ testProperty "simple convergence" $ \setup -> prop_simple_leader_schedule_convergence setup ] prop_simple_leader_schedule_convergence :: TestSetup -> Property prop_simple_leader_schedule_convergence TestSetup { setupK = k , setupTestConfig = testConfig , setupEpochSize = epochSize , setupNodeJoinPlan = nodeJoinPlan , setupLeaderSchedule = schedule , setupSlotLength = slotLength } = counterexample (tracesToDot testOutputNodes) $ prop_general PropGeneralArgs { pgaBlockProperty = prop_validSimpleBlock , pgaCountTxs = countSimpleGenTxs , pgaExpectedCannotForge = noExpectedCannotForges , pgaFirstBlockNo = 0 , pgaFixedMaxForkLength = Nothing , pgaFixedSchedule = Just schedule , pgaSecurityParam = k , pgaTestConfig = testConfig , pgaTestConfigB = testConfigB } testOutput where TestConfig{numCoreNodes} = testConfig testConfigB = TestConfigB { forgeEbbEnv = Nothing , future = singleEraFuture slotLength epochSize , messageDelay = noCalcMessageDelay , nodeJoinPlan , nodeRestarts = noRestarts , txGenExtra = () , version = newestVersion (Proxy @MockPraosRuleBlock) } -- this is entirely ignored because of the 'WithLeaderSchedule' combinator dummyF = 0.5 testOutput@TestOutput{testOutputNodes} = runTestNetwork testConfig testConfigB TestConfigMB { nodeInfo = \nid -> plainTestNodeInitialization $ protocolInfoPraosRule numCoreNodes nid PraosParams { praosSecurityParam = k , praosSlotsPerEpoch = unEpochSize epochSize , praosLeaderF = dummyF } (HardFork.defaultEraParams k slotLength) schedule emptyPraosEvolvingStake , mkRekeyM = Nothing } {------------------------------------------------------------------------------- Dependent generation and shrinking of leader schedules -------------------------------------------------------------------------------} genLeaderSchedule :: SecurityParam -> NumSlots -> NumCoreNodes -> NodeJoinPlan -> Gen LeaderSchedule genLeaderSchedule k (NumSlots numSlots) numCoreNodes nodeJoinPlan = flip suchThat (consensusExpected k nodeJoinPlan) $ do leaders <- replicateM (fromIntegral numSlots) $ frequency [ ( 4, pick 0) , ( 2, pick 1) , ( 1, pick 2) , ( 1, pick 3) ] return $ LeaderSchedule $ Map.fromList $ zip [0..] leaders where pick :: Int -> Gen [CoreNodeId] pick = go (enumCoreNodes numCoreNodes) where go :: [CoreNodeId] -> Int -> Gen [CoreNodeId] go [] _ = return [] go _ 0 = return [] go nids n = do nid <- elements nids xs <- go (filter (/= nid) nids) (n - 1) return $ nid : xs _shrinkLeaderSchedule :: NumSlots -> LeaderSchedule -> [LeaderSchedule] _shrinkLeaderSchedule (NumSlots numSlots) (LeaderSchedule m) = [ LeaderSchedule m' | slot <- [0 .. fromIntegral numSlots - 1] , m' <- reduceSlot slot m ] where reduceSlot :: SlotNo -> Map SlotNo [CoreNodeId] -> [Map SlotNo [CoreNodeId]] reduceSlot s m' = [Map.insert s xs m' | xs <- reduceList $ m' Map.! s] reduceList :: [a] -> [[a]] reduceList [] = [] reduceList [_] = [] reduceList (x : xs) = xs : map (x :) (reduceList xs)
null
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/54cd34e68afafe957feef485ceaee3171efb0693/ouroboros-consensus-mock-test/test/Test/ThreadNet/LeaderSchedule.hs
haskell
# LANGUAGE NamedFieldPuns # ^ Note: we don't think this value actually matters, since this test overrides the leader schedule. TODO shrink this is entirely ignored because of the 'WithLeaderSchedule' combinator ------------------------------------------------------------------------------ Dependent generation and shrinking of leader schedules ------------------------------------------------------------------------------
# LANGUAGE RecordWildCards # # LANGUAGE TypeApplications # module Test.ThreadNet.LeaderSchedule (tests) where import Control.Monad (replicateM) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Test.QuickCheck import Test.Tasty import Test.Tasty.QuickCheck import Ouroboros.Consensus.Block import Ouroboros.Consensus.BlockchainTime import Ouroboros.Consensus.Config.SecurityParam import qualified Ouroboros.Consensus.HardFork.History as HardFork import Ouroboros.Consensus.Mock.Ledger import Ouroboros.Consensus.Mock.Node () import Ouroboros.Consensus.Mock.Node.PraosRule import Ouroboros.Consensus.Mock.Protocol.LeaderSchedule import Ouroboros.Consensus.Mock.Protocol.Praos import Ouroboros.Consensus.Node.ProtocolInfo import Ouroboros.Consensus.NodeId import Test.ThreadNet.General import Test.ThreadNet.TxGen.Mock () import Test.ThreadNet.Util import Test.ThreadNet.Util.HasCreator.Mock () import Test.ThreadNet.Util.NodeJoinPlan import Test.ThreadNet.Util.NodeRestarts import Test.ThreadNet.Util.NodeToNodeVersion import Test.ThreadNet.Util.SimpleBlock import Test.Util.HardFork.Future (singleEraFuture) import Test.Util.Orphans.Arbitrary () import Test.Util.Slots (NumSlots (..)) data TestSetup = TestSetup { setupK :: SecurityParam , setupTestConfig :: TestConfig , setupEpochSize :: EpochSize , setupNodeJoinPlan :: NodeJoinPlan , setupLeaderSchedule :: LeaderSchedule , setupSlotLength :: SlotLength } deriving (Show) instance Arbitrary TestSetup where arbitrary = do TODO k > 1 as a workaround for Issue # 1511 . k <- SecurityParam <$> choose (2, 10) epochSize <- EpochSize <$> choose (1, 10) slotLength <- arbitrary testConfig <- arbitrary let TestConfig{numCoreNodes, numSlots} = testConfig nodeJoinPlan <- genNodeJoinPlan numCoreNodes numSlots leaderSchedule <- genLeaderSchedule k numSlots numCoreNodes nodeJoinPlan pure $ TestSetup k testConfig epochSize nodeJoinPlan leaderSchedule slotLength tests :: TestTree tests = testGroup "LeaderSchedule" [ testProperty "simple convergence" $ \setup -> prop_simple_leader_schedule_convergence setup ] prop_simple_leader_schedule_convergence :: TestSetup -> Property prop_simple_leader_schedule_convergence TestSetup { setupK = k , setupTestConfig = testConfig , setupEpochSize = epochSize , setupNodeJoinPlan = nodeJoinPlan , setupLeaderSchedule = schedule , setupSlotLength = slotLength } = counterexample (tracesToDot testOutputNodes) $ prop_general PropGeneralArgs { pgaBlockProperty = prop_validSimpleBlock , pgaCountTxs = countSimpleGenTxs , pgaExpectedCannotForge = noExpectedCannotForges , pgaFirstBlockNo = 0 , pgaFixedMaxForkLength = Nothing , pgaFixedSchedule = Just schedule , pgaSecurityParam = k , pgaTestConfig = testConfig , pgaTestConfigB = testConfigB } testOutput where TestConfig{numCoreNodes} = testConfig testConfigB = TestConfigB { forgeEbbEnv = Nothing , future = singleEraFuture slotLength epochSize , messageDelay = noCalcMessageDelay , nodeJoinPlan , nodeRestarts = noRestarts , txGenExtra = () , version = newestVersion (Proxy @MockPraosRuleBlock) } dummyF = 0.5 testOutput@TestOutput{testOutputNodes} = runTestNetwork testConfig testConfigB TestConfigMB { nodeInfo = \nid -> plainTestNodeInitialization $ protocolInfoPraosRule numCoreNodes nid PraosParams { praosSecurityParam = k , praosSlotsPerEpoch = unEpochSize epochSize , praosLeaderF = dummyF } (HardFork.defaultEraParams k slotLength) schedule emptyPraosEvolvingStake , mkRekeyM = Nothing } genLeaderSchedule :: SecurityParam -> NumSlots -> NumCoreNodes -> NodeJoinPlan -> Gen LeaderSchedule genLeaderSchedule k (NumSlots numSlots) numCoreNodes nodeJoinPlan = flip suchThat (consensusExpected k nodeJoinPlan) $ do leaders <- replicateM (fromIntegral numSlots) $ frequency [ ( 4, pick 0) , ( 2, pick 1) , ( 1, pick 2) , ( 1, pick 3) ] return $ LeaderSchedule $ Map.fromList $ zip [0..] leaders where pick :: Int -> Gen [CoreNodeId] pick = go (enumCoreNodes numCoreNodes) where go :: [CoreNodeId] -> Int -> Gen [CoreNodeId] go [] _ = return [] go _ 0 = return [] go nids n = do nid <- elements nids xs <- go (filter (/= nid) nids) (n - 1) return $ nid : xs _shrinkLeaderSchedule :: NumSlots -> LeaderSchedule -> [LeaderSchedule] _shrinkLeaderSchedule (NumSlots numSlots) (LeaderSchedule m) = [ LeaderSchedule m' | slot <- [0 .. fromIntegral numSlots - 1] , m' <- reduceSlot slot m ] where reduceSlot :: SlotNo -> Map SlotNo [CoreNodeId] -> [Map SlotNo [CoreNodeId]] reduceSlot s m' = [Map.insert s xs m' | xs <- reduceList $ m' Map.! s] reduceList :: [a] -> [[a]] reduceList [] = [] reduceList [_] = [] reduceList (x : xs) = xs : map (x :) (reduceList xs)
8d69ade7b7d5684b05150c1702ecede12098a62abbf2f1bc1f0cc3116b221af1
unnohideyuki/bunny
sample306.hs
x = 1.0 :: Float y = 2.0 :: Float z = 0.0 :: Float t = 10.0 :: Float main = do print $ succ (2.3 :: Float) print $ pred (2.3 :: Float) print $ (toEnum 3 :: Float) print $ fromEnum (2.3 :: Float) print $ take 10 $ [x..] print $ take 10 $ [y, x ..] print $ [z .. t] print $ [z, y .. t]
null
https://raw.githubusercontent.com/unnohideyuki/bunny/501856ff48f14b252b674585f25a2bf3801cb185/compiler/test/samples/sample306.hs
haskell
x = 1.0 :: Float y = 2.0 :: Float z = 0.0 :: Float t = 10.0 :: Float main = do print $ succ (2.3 :: Float) print $ pred (2.3 :: Float) print $ (toEnum 3 :: Float) print $ fromEnum (2.3 :: Float) print $ take 10 $ [x..] print $ take 10 $ [y, x ..] print $ [z .. t] print $ [z, y .. t]
740cc8ee3edcd80079b55c96b4271dbe8576195e2b9f40e9dac4b75a9c41578b
dwayne/eopl3
ex2.9.rkt
#lang racket Exercise 2.9 ;; ;; Add an observer called has-binding? and ;; implement it using the a-list representation. (define (empty-env) '()) (define (empty-env? env) (null? env)) (define (extend-env var val env) (cons (cons var val) env)) (define (apply-env env search-var) (if (empty-env? env) (error 'apply-env "No binding for ~s" search-var) (let ([saved-var (caar env)]) (if (symbol=? search-var saved-var) (cdar env) (apply-env (cdr env) search-var))))) (define (has-binding? env search-var) (if (empty-env? env) #f (let ([saved-var (caar env)]) (if (symbol=? search-var saved-var) #t (has-binding? (cdr env) search-var))))) (module+ test (require rackunit) (let ([env (extend-env 'd 6 (extend-env 'y 8 (extend-env 'x 7 (extend-env 'y 14 (empty-env)))))]) (check-eq? (apply-env env 'd) 6) (check-eq? (apply-env env 'y) 8) (check-eq? (apply-env env 'x) 7) (check-exn #rx"No binding for a" (lambda () (apply-env env 'a))) (check-false (empty-env? env)) (check-true (has-binding? env 'd)) (check-true (has-binding? env 'y)) (check-true (has-binding? env 'x)) (check-false (has-binding? env 'a))) (check-true (empty-env? (empty-env))))
null
https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/02-ch2/racket/ex2.9.rkt
racket
Add an observer called has-binding? and implement it using the a-list representation.
#lang racket Exercise 2.9 (define (empty-env) '()) (define (empty-env? env) (null? env)) (define (extend-env var val env) (cons (cons var val) env)) (define (apply-env env search-var) (if (empty-env? env) (error 'apply-env "No binding for ~s" search-var) (let ([saved-var (caar env)]) (if (symbol=? search-var saved-var) (cdar env) (apply-env (cdr env) search-var))))) (define (has-binding? env search-var) (if (empty-env? env) #f (let ([saved-var (caar env)]) (if (symbol=? search-var saved-var) #t (has-binding? (cdr env) search-var))))) (module+ test (require rackunit) (let ([env (extend-env 'd 6 (extend-env 'y 8 (extend-env 'x 7 (extend-env 'y 14 (empty-env)))))]) (check-eq? (apply-env env 'd) 6) (check-eq? (apply-env env 'y) 8) (check-eq? (apply-env env 'x) 7) (check-exn #rx"No binding for a" (lambda () (apply-env env 'a))) (check-false (empty-env? env)) (check-true (has-binding? env 'd)) (check-true (has-binding? env 'y)) (check-true (has-binding? env 'x)) (check-false (has-binding? env 'a))) (check-true (empty-env? (empty-env))))
aa29b4dc0bb736c17112bb91e6493b2159489999cfecb1bb84234db45830ba13
emina/rosette
install.rkt
#lang racket/base ;; Check whether z3 is installed during package setup. ;; If missing, builds & links a z3 binary. (provide pre-installer post-installer) (require racket/match racket/file racket/port net/url file/unzip) We need to run the Z3 installer as a pre - install step , because building the documentation relies on Z3 being available . But pre - install is so early in ; the build that its output gets pushed off screen by the later steps. So we ; use this little hack to repeat the failure message as a post-install step, ; which happens at the very end of the install and so makes the error message ; far more obvious. (define z3-install-failure #f) (define z3-version "4.8.8") (define (print-failure path msg) (printf "\n\n********** Failed to install Z3 **********\n\n") (printf "Rosette installed successfully, but wasn't able to install the Z3 SMT solver.\n\n") (printf "You'll need to manually install a Z3 binary at this location:\n") (printf " ~a\n" path) (printf "or anywhere that is on your PATH. Alternatively, in your programs, you can\n") (printf "construct a solver object manually:\n") (printf " (current-solver (z3 #:path \"/path/to/z3\"))\n\n") (printf "Note that Rosette ships with a specific release of Z3 (v~a). Installing a\n" z3-version) (printf "different version of Z3 may change the performance of Rosette programs.\n\n") (printf "The problem was:\n ~a\n\n" msg) (printf "**********\n\n\n")) (define (post-installer collections-top-path) (match z3-install-failure [(cons z3-path msg) (print-failure z3-path msg)] [_ (void)])) (define (pre-installer collections-top-path racl-path) (define bin-path (simplify-path (build-path racl-path ".." "bin"))) (define z3-path (build-path bin-path "z3")) (with-handlers ([exn:fail? (lambda (e) (set! z3-install-failure (cons z3-path (exn-message e))) (print-failure z3-path (exn-message e)))]) (unless (custom-z3-symlink? z3-path) (define-values (z3-url z3-path-in-zip) (get-z3-url)) (define z3-port (get-pure-port (string->url z3-url) #:redirections 10)) (make-directory* bin-path) ;; Ensure that `bin-path` exists Delete old version of Z3 , if any (parameterize ([current-directory bin-path]) (call-with-unzip z3-port (λ (dir) (copy-directory/files (build-path dir z3-path-in-zip) z3-path))) ;; Unzipping loses file permissions, so we reset the z3 binary here (file-or-directory-permissions z3-path (if (equal? (system-type) 'windows) #o777 #o755)))))) (define (custom-z3-symlink? z3-path) (and (file-exists? z3-path) (let ([p (simplify-path z3-path)]) (not (equal? (resolve-path p) p))))) (define (get-z3-url) (define site "") (define-values (os exe) (match (list (system-type 'os*) (system-type 'arch)) ['(linux x86_64) (values "x64-ubuntu-16.04" "z3")] TODO : use a native aarch64 Z3 build on macOS when we upgrade to a newer Z3 [`(macosx ,_) (values "x64-osx-10.14.6" "z3")] ['(windows x86_64) (values "x64-win" "z3.exe")] [any (raise-user-error 'get-z3-url "No Z3 binary available for system type '~a" any)])) (define name (format "z3-~a-~a" z3-version os)) (values (format "~a/z3-~a/~a.zip" site z3-version name) (format "~a/bin/~a" name exe))) ;; A copy of net/url's get-pure-port/headers, except with the Location header ;; for redirects made case-insensitive, fixing (require net/http-client net/url-connect) (define (get-pure-port url #:redirections [redirections 0]) (let redirection-loop ([redirections redirections] [url url]) (define hc (http-conn-open (url-host url) #:ssl? (if (equal? "https" (url-scheme url)) (current-https-protocol) #f))) (define access-string (url->string RFCs 1945 and 2616 say : ;; Note that the absolute path cannot be empty; if none is present in the original URI , it must be given as " / " ( the server root ) . (let-values ([(abs? path) (if (null? (url-path url)) (values #t (list (make-path/param "" '()))) (values (url-path-absolute? url) (url-path url)))]) (make-url #f #f #f #f abs? path (url-query url) (url-fragment url))))) (http-conn-send! hc access-string #:method #"GET" #:content-decode '()) (define-values (status headers response-port) (http-conn-recv! hc #:method #"GET" #:close? #t #:content-decode '())) (define new-url (ormap (λ (h) (match (regexp-match #rx#"^[Ll]ocation: (.*)$" h) [#f #f] [(list _ m1b) (define m1 (bytes->string/utf-8 m1b)) (with-handlers ((exn:fail? (λ (x) #f))) (define next-url (string->url m1)) (make-url (or (url-scheme next-url) (url-scheme url)) (or (url-user next-url) (url-user url)) (or (url-host next-url) (url-host url)) (or (url-port next-url) (url-port url)) (url-path-absolute? next-url) (url-path next-url) (url-query next-url) (url-fragment next-url)))])) headers)) (define redirection-status-line? (regexp-match #rx#"^HTTP/[0-9]+[.][0-9]+ 3[0-9][0-9]" status)) (cond [(and redirection-status-line? new-url (not (zero? redirections))) (redirection-loop (- redirections 1) new-url)] [else response-port])))
null
https://raw.githubusercontent.com/emina/rosette/ec1a0db46455e289de0f5802ff6bfc04cd32f5c0/rosette/private/install.rkt
racket
Check whether z3 is installed during package setup. If missing, builds & links a z3 binary. the build that its output gets pushed off screen by the later steps. So we use this little hack to repeat the failure message as a post-install step, which happens at the very end of the install and so makes the error message far more obvious. Ensure that `bin-path` exists Unzipping loses file permissions, so we reset the z3 binary here A copy of net/url's get-pure-port/headers, except with the Location header for redirects made case-insensitive, fixing Note that the absolute path cannot be empty; if none is present in
#lang racket/base (provide pre-installer post-installer) (require racket/match racket/file racket/port net/url file/unzip) We need to run the Z3 installer as a pre - install step , because building the documentation relies on Z3 being available . But pre - install is so early in (define z3-install-failure #f) (define z3-version "4.8.8") (define (print-failure path msg) (printf "\n\n********** Failed to install Z3 **********\n\n") (printf "Rosette installed successfully, but wasn't able to install the Z3 SMT solver.\n\n") (printf "You'll need to manually install a Z3 binary at this location:\n") (printf " ~a\n" path) (printf "or anywhere that is on your PATH. Alternatively, in your programs, you can\n") (printf "construct a solver object manually:\n") (printf " (current-solver (z3 #:path \"/path/to/z3\"))\n\n") (printf "Note that Rosette ships with a specific release of Z3 (v~a). Installing a\n" z3-version) (printf "different version of Z3 may change the performance of Rosette programs.\n\n") (printf "The problem was:\n ~a\n\n" msg) (printf "**********\n\n\n")) (define (post-installer collections-top-path) (match z3-install-failure [(cons z3-path msg) (print-failure z3-path msg)] [_ (void)])) (define (pre-installer collections-top-path racl-path) (define bin-path (simplify-path (build-path racl-path ".." "bin"))) (define z3-path (build-path bin-path "z3")) (with-handlers ([exn:fail? (lambda (e) (set! z3-install-failure (cons z3-path (exn-message e))) (print-failure z3-path (exn-message e)))]) (unless (custom-z3-symlink? z3-path) (define-values (z3-url z3-path-in-zip) (get-z3-url)) (define z3-port (get-pure-port (string->url z3-url) #:redirections 10)) Delete old version of Z3 , if any (parameterize ([current-directory bin-path]) (call-with-unzip z3-port (λ (dir) (copy-directory/files (build-path dir z3-path-in-zip) z3-path))) (file-or-directory-permissions z3-path (if (equal? (system-type) 'windows) #o777 #o755)))))) (define (custom-z3-symlink? z3-path) (and (file-exists? z3-path) (let ([p (simplify-path z3-path)]) (not (equal? (resolve-path p) p))))) (define (get-z3-url) (define site "") (define-values (os exe) (match (list (system-type 'os*) (system-type 'arch)) ['(linux x86_64) (values "x64-ubuntu-16.04" "z3")] TODO : use a native aarch64 Z3 build on macOS when we upgrade to a newer Z3 [`(macosx ,_) (values "x64-osx-10.14.6" "z3")] ['(windows x86_64) (values "x64-win" "z3.exe")] [any (raise-user-error 'get-z3-url "No Z3 binary available for system type '~a" any)])) (define name (format "z3-~a-~a" z3-version os)) (values (format "~a/z3-~a/~a.zip" site z3-version name) (format "~a/bin/~a" name exe))) (require net/http-client net/url-connect) (define (get-pure-port url #:redirections [redirections 0]) (let redirection-loop ([redirections redirections] [url url]) (define hc (http-conn-open (url-host url) #:ssl? (if (equal? "https" (url-scheme url)) (current-https-protocol) #f))) (define access-string (url->string RFCs 1945 and 2616 say : the original URI , it must be given as " / " ( the server root ) . (let-values ([(abs? path) (if (null? (url-path url)) (values #t (list (make-path/param "" '()))) (values (url-path-absolute? url) (url-path url)))]) (make-url #f #f #f #f abs? path (url-query url) (url-fragment url))))) (http-conn-send! hc access-string #:method #"GET" #:content-decode '()) (define-values (status headers response-port) (http-conn-recv! hc #:method #"GET" #:close? #t #:content-decode '())) (define new-url (ormap (λ (h) (match (regexp-match #rx#"^[Ll]ocation: (.*)$" h) [#f #f] [(list _ m1b) (define m1 (bytes->string/utf-8 m1b)) (with-handlers ((exn:fail? (λ (x) #f))) (define next-url (string->url m1)) (make-url (or (url-scheme next-url) (url-scheme url)) (or (url-user next-url) (url-user url)) (or (url-host next-url) (url-host url)) (or (url-port next-url) (url-port url)) (url-path-absolute? next-url) (url-path next-url) (url-query next-url) (url-fragment next-url)))])) headers)) (define redirection-status-line? (regexp-match #rx#"^HTTP/[0-9]+[.][0-9]+ 3[0-9][0-9]" status)) (cond [(and redirection-status-line? new-url (not (zero? redirections))) (redirection-loop (- redirections 1) new-url)] [else response-port])))
9e9d5775c04a9d2f1d4e20628333b57dd8e70cd0fcd1b3e2bcbe351b5e99cb6e
fp-works/2019-winter-Haskell-school
Exercise01Spec.hs
module CIS194.Homework01.Exercise01Spec where import CIS194.Homework01.Exercise01 import Test.Tasty.Hspec spec_toDigits :: Spec spec_toDigits = do it "returns an expected list for a negative integer" $ toDigits (-123) `shouldBe` [1..3] it "returns [0] for 0" $ toDigits 0 `shouldBe` [0] it "returns an expected list for a positive integer" $ toDigits 12345 `shouldBe` [1..5] spec_toDigitsRev :: Spec spec_toDigitsRev = do it "returns the expected list for a negative integer" $ toDigitsRev (-123) `shouldBe` [3, 2, 1] it "returns [0] for 0" $ toDigitsRev 0 `shouldBe` [0] it "returns the expected list for a positive integer" $ toDigitsRev 378921 `shouldBe` [1, 2, 9, 8, 7, 3]
null
https://raw.githubusercontent.com/fp-works/2019-winter-Haskell-school/823b67f019b9e7bc0d3be36711c0cc7da4eba7d2/cis194/week1/daniel-deng/test/CIS194/Homework01/Exercise01Spec.hs
haskell
module CIS194.Homework01.Exercise01Spec where import CIS194.Homework01.Exercise01 import Test.Tasty.Hspec spec_toDigits :: Spec spec_toDigits = do it "returns an expected list for a negative integer" $ toDigits (-123) `shouldBe` [1..3] it "returns [0] for 0" $ toDigits 0 `shouldBe` [0] it "returns an expected list for a positive integer" $ toDigits 12345 `shouldBe` [1..5] spec_toDigitsRev :: Spec spec_toDigitsRev = do it "returns the expected list for a negative integer" $ toDigitsRev (-123) `shouldBe` [3, 2, 1] it "returns [0] for 0" $ toDigitsRev 0 `shouldBe` [0] it "returns the expected list for a positive integer" $ toDigitsRev 378921 `shouldBe` [1, 2, 9, 8, 7, 3]
6a7bd843572fb70b007160131830ecc31d314599a8b22508e47fe30c973fe463
byorgey/AoC
24.hs
-- I ultimately solved day 24 by hand, but used the code in this -- module to help me explore! {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DeriveGeneric # # LANGUAGE LambdaCase # {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE TemplateHaskell #-} # LANGUAGE TupleSections # import Control.Applicative (many, (<|>)) import Control.Arrow ((>>>)) import Control.Lens import Control.Monad.Reader (ReaderT, ask, runReaderT) import Control.Monad.State (State, execState) import Data.Data (Data) import Data.Data.Lens (uniplate) import Data.List (scanl') import Data.Map (Map, (!)) import qualified Data.Map.Strict as M import Data.Maybe (fromJust) import Data.Void (Void) import GHC.Generics (Generic) import Text.Megaparsec (Parsec, parse) import Text.Megaparsec.Char (space, string) import Text.Megaparsec.Char.Lexer (decimal, signed) ------------------------------------------------------------ AST data Register = W | X | Y | Z deriving (Eq, Ord, Show, Read, Bounded, Enum) data RVal = Reg Register | Val Integer deriving (Eq, Ord, Show) data Instruction = Inp Register | Bin Op Register RVal deriving (Eq, Ord, Show) data Op = Add | Mul | Div | Mod | Eql deriving (Eq, Ord, Show, Generic, Data) ------------------------------------------------------------ Parser type Parser = Parsec Void String readParser p = parse p "" >>> either undefined id parseProgram :: Parser [Instruction] parseProgram = many (parseInstruction <* space) parseInstruction :: Parser Instruction parseInstruction = Inp <$> (string "inp" *> space *> parseReg) <|> Bin <$> parseOp <*> (space *> parseReg) <*> (space *> parseRVal) parseOp :: Parser Op parseOp = Add <$ string "add" <|> Mul <$ string "mul" <|> Div <$ string "div" <|> Mod <$ string "mod" <|> Eql <$ string "eql" parseReg :: Parser Register parseReg = W <$ string "w" <|> X <$ string "x" <|> Y <$ string "y" <|> Z <$ string "z" parseRVal :: Parser RVal parseRVal = Reg <$> parseReg <|> Val <$> signed space decimal ------------------------------------------------------------ -- Interpretation data ALU v = ALU { _inputs :: [v], _registers :: Map Register v } deriving (Eq, Show) makeLenses ''ALU type ALUM v = ReaderT (Semantics v) (State (ALU v)) data Semantics v = Semantics { litSem :: Integer -> v , inputSem :: Register -> ALUM v () , binSem :: Op -> Register -> RVal -> ALUM v () } runALU :: Semantics v -> [v] -> [Instruction] -> ALU v runALU sem inp is = execState (runReaderT (exec is) sem) (ALU inp (M.fromList (map (,zero) [W .. Z]))) where zero = litSem sem 0 exec :: [Instruction] -> ALUM v () exec = mapM_ execOne execOne :: Instruction -> ALUM v () execOne (Inp r) = ask >>= \sem -> inputSem sem r execOne (Bin op l r) = ask >>= \sem -> binSem sem op l r getInput :: ALUM v v getInput = do is <- use inputs inputs .= tail is return (head is) input :: Register -> ALUM v () input r = do v <- getInput registers . ix r .= v bin :: (Op -> v -> v -> v) -> Op -> Register -> RVal -> ALUM v () bin eval op l r = do v1 <- fromJust <$> use (registers . at l) v2 <- evalRVal r let v = eval op v1 v2 registers . ix l .= v evalRVal :: RVal -> ALUM v v evalRVal (Reg r) = fromJust <$> use (registers . at r) evalRVal (Val v) = ask >>= \sem -> return (litSem sem v) -------------------------------------------------- -- Normal integer semantics evalOp :: Op -> Integer -> Integer -> Integer evalOp = \case Add -> (+) Mul -> (*) Div -> div Mod -> mod Eql -> (\x y -> if x == y then 1 else 0) intSem :: Semantics Integer intSem = Semantics id input (bin evalOp) runALUInt :: Integer -> [Instruction] -> ALU Integer runALUInt inp = runALU intSem (digits inp) digits = reverse . explode where explode 0 = [] explode n = n `mod` 10 : explode (n `div` 10) -------------------------------------------------- -- Algebraic semantics data Expr = ELit Integer | EInput Int | EBin Op Expr Expr deriving (Eq, Ord, Show, Generic, Data) instance Plated Expr where plate = uniplate exprSem :: Semantics Expr exprSem = Semantics ELit input (bin EBin) runALUExpr :: [Instruction] -> Map Register Expr runALUExpr = runALU exprSem (map EInput [0..]) >>> view registers >>> fmap simplify simplify :: Expr -> Expr simplify = transform simple where simple :: Expr -> Expr simple (EBin Add (ELit 0) x) = x simple (EBin Add x (ELit 0)) = x simple (EBin Mul (ELit 0) _) = ELit 0 simple (EBin Mul _ (ELit 0)) = ELit 0 simple (EBin Mul (ELit 1) x) = x simple (EBin Mul x (ELit 1)) = x simple (EBin op (ELit x) (ELit y)) = ELit (evalOp op x y) simple e = e ------------------------------------------------------------ pattern TheLoop a b c = [Inp W,Bin Mul X (Val 0),Bin Add X (Reg Z),Bin Mod X (Val 26),Bin Div Z (Val a),Bin Add X (Val b),Bin Eql X (Reg W),Bin Eql X (Val 0),Bin Mul Y (Val 0),Bin Add Y (Val 25),Bin Mul Y (Reg X),Bin Add Y (Val 1),Bin Mul Z (Reg Y),Bin Mul Y (Val 0),Bin Add Y (Reg W),Bin Add Y (Val c),Bin Mul Y (Reg X),Bin Add Z (Reg Y)] match :: [Instruction] -> Maybe (Integer, Integer, Integer) match (TheLoop a b c) = Just (a,b,c) match _= Nothing vs :: [(Integer,Integer,Integer)] vs = [(1,11,8),(1,14,13),(1,10,2),(26,0,7),(1,12,11),(1,12,4),(1,12,13),(26,-8,13),(26,-9,10),(1,11,1),(26,0,2),(26,-5,14),(26,-6,6),(26,-12,14)] gen :: (Integer,Integer,Integer) -> [Instruction] gen (a,b,c) = TheLoop a b c type Sim a = (Integer,Integer,Integer) -> Integer -> (a -> a) sim :: Sim Integer sim (a,b,c) inp z | z `mod` 26 + b == inp = z' | otherwise = 26*z' + inp + c where z' = z `div` a sim2 :: Sim [Integer] sim2 (a,b,c) inp [] = if inp == b then [] else [inp+c] sim2 (a,b,c) inp (z:zs) = if z + b == inp then zs' else (inp+c):zs' where zs' | a == 26 = zs | otherwise = z:zs runSim :: Sim a -> a -> [(Integer, Integer, Integer)] -> Integer -> [a] runSim s zero steps input = scanl' (\z (step,i) -> s step i z) zero (zip steps (digits input)) ok :: Integer -> Bool ok inp = Just (last (runSim sim 0 vs inp)) == (runALUInt inp (concatMap gen vs) ^. registers . at Z) ok2 :: Integer -> Bool ok2 inp = Just (foldr (\d n -> d + 26*n) 0 (last (runSim sim2 [] vs inp))) == (runALUInt inp (concatMap gen vs) ^. registers . at Z)
null
https://raw.githubusercontent.com/byorgey/AoC/1789a50667dacbe3aeac5c33d12463ba4da5ea71/2021/24/24.hs
haskell
I ultimately solved day 24 by hand, but used the code in this module to help me explore! # LANGUAGE DeriveDataTypeable # # LANGUAGE PatternSynonyms # # LANGUAGE TemplateHaskell # ---------------------------------------------------------- ---------------------------------------------------------- ---------------------------------------------------------- Interpretation ------------------------------------------------ Normal integer semantics ------------------------------------------------ Algebraic semantics ----------------------------------------------------------
# LANGUAGE DeriveGeneric # # LANGUAGE LambdaCase # # LANGUAGE TupleSections # import Control.Applicative (many, (<|>)) import Control.Arrow ((>>>)) import Control.Lens import Control.Monad.Reader (ReaderT, ask, runReaderT) import Control.Monad.State (State, execState) import Data.Data (Data) import Data.Data.Lens (uniplate) import Data.List (scanl') import Data.Map (Map, (!)) import qualified Data.Map.Strict as M import Data.Maybe (fromJust) import Data.Void (Void) import GHC.Generics (Generic) import Text.Megaparsec (Parsec, parse) import Text.Megaparsec.Char (space, string) import Text.Megaparsec.Char.Lexer (decimal, signed) AST data Register = W | X | Y | Z deriving (Eq, Ord, Show, Read, Bounded, Enum) data RVal = Reg Register | Val Integer deriving (Eq, Ord, Show) data Instruction = Inp Register | Bin Op Register RVal deriving (Eq, Ord, Show) data Op = Add | Mul | Div | Mod | Eql deriving (Eq, Ord, Show, Generic, Data) Parser type Parser = Parsec Void String readParser p = parse p "" >>> either undefined id parseProgram :: Parser [Instruction] parseProgram = many (parseInstruction <* space) parseInstruction :: Parser Instruction parseInstruction = Inp <$> (string "inp" *> space *> parseReg) <|> Bin <$> parseOp <*> (space *> parseReg) <*> (space *> parseRVal) parseOp :: Parser Op parseOp = Add <$ string "add" <|> Mul <$ string "mul" <|> Div <$ string "div" <|> Mod <$ string "mod" <|> Eql <$ string "eql" parseReg :: Parser Register parseReg = W <$ string "w" <|> X <$ string "x" <|> Y <$ string "y" <|> Z <$ string "z" parseRVal :: Parser RVal parseRVal = Reg <$> parseReg <|> Val <$> signed space decimal data ALU v = ALU { _inputs :: [v], _registers :: Map Register v } deriving (Eq, Show) makeLenses ''ALU type ALUM v = ReaderT (Semantics v) (State (ALU v)) data Semantics v = Semantics { litSem :: Integer -> v , inputSem :: Register -> ALUM v () , binSem :: Op -> Register -> RVal -> ALUM v () } runALU :: Semantics v -> [v] -> [Instruction] -> ALU v runALU sem inp is = execState (runReaderT (exec is) sem) (ALU inp (M.fromList (map (,zero) [W .. Z]))) where zero = litSem sem 0 exec :: [Instruction] -> ALUM v () exec = mapM_ execOne execOne :: Instruction -> ALUM v () execOne (Inp r) = ask >>= \sem -> inputSem sem r execOne (Bin op l r) = ask >>= \sem -> binSem sem op l r getInput :: ALUM v v getInput = do is <- use inputs inputs .= tail is return (head is) input :: Register -> ALUM v () input r = do v <- getInput registers . ix r .= v bin :: (Op -> v -> v -> v) -> Op -> Register -> RVal -> ALUM v () bin eval op l r = do v1 <- fromJust <$> use (registers . at l) v2 <- evalRVal r let v = eval op v1 v2 registers . ix l .= v evalRVal :: RVal -> ALUM v v evalRVal (Reg r) = fromJust <$> use (registers . at r) evalRVal (Val v) = ask >>= \sem -> return (litSem sem v) evalOp :: Op -> Integer -> Integer -> Integer evalOp = \case Add -> (+) Mul -> (*) Div -> div Mod -> mod Eql -> (\x y -> if x == y then 1 else 0) intSem :: Semantics Integer intSem = Semantics id input (bin evalOp) runALUInt :: Integer -> [Instruction] -> ALU Integer runALUInt inp = runALU intSem (digits inp) digits = reverse . explode where explode 0 = [] explode n = n `mod` 10 : explode (n `div` 10) data Expr = ELit Integer | EInput Int | EBin Op Expr Expr deriving (Eq, Ord, Show, Generic, Data) instance Plated Expr where plate = uniplate exprSem :: Semantics Expr exprSem = Semantics ELit input (bin EBin) runALUExpr :: [Instruction] -> Map Register Expr runALUExpr = runALU exprSem (map EInput [0..]) >>> view registers >>> fmap simplify simplify :: Expr -> Expr simplify = transform simple where simple :: Expr -> Expr simple (EBin Add (ELit 0) x) = x simple (EBin Add x (ELit 0)) = x simple (EBin Mul (ELit 0) _) = ELit 0 simple (EBin Mul _ (ELit 0)) = ELit 0 simple (EBin Mul (ELit 1) x) = x simple (EBin Mul x (ELit 1)) = x simple (EBin op (ELit x) (ELit y)) = ELit (evalOp op x y) simple e = e pattern TheLoop a b c = [Inp W,Bin Mul X (Val 0),Bin Add X (Reg Z),Bin Mod X (Val 26),Bin Div Z (Val a),Bin Add X (Val b),Bin Eql X (Reg W),Bin Eql X (Val 0),Bin Mul Y (Val 0),Bin Add Y (Val 25),Bin Mul Y (Reg X),Bin Add Y (Val 1),Bin Mul Z (Reg Y),Bin Mul Y (Val 0),Bin Add Y (Reg W),Bin Add Y (Val c),Bin Mul Y (Reg X),Bin Add Z (Reg Y)] match :: [Instruction] -> Maybe (Integer, Integer, Integer) match (TheLoop a b c) = Just (a,b,c) match _= Nothing vs :: [(Integer,Integer,Integer)] vs = [(1,11,8),(1,14,13),(1,10,2),(26,0,7),(1,12,11),(1,12,4),(1,12,13),(26,-8,13),(26,-9,10),(1,11,1),(26,0,2),(26,-5,14),(26,-6,6),(26,-12,14)] gen :: (Integer,Integer,Integer) -> [Instruction] gen (a,b,c) = TheLoop a b c type Sim a = (Integer,Integer,Integer) -> Integer -> (a -> a) sim :: Sim Integer sim (a,b,c) inp z | z `mod` 26 + b == inp = z' | otherwise = 26*z' + inp + c where z' = z `div` a sim2 :: Sim [Integer] sim2 (a,b,c) inp [] = if inp == b then [] else [inp+c] sim2 (a,b,c) inp (z:zs) = if z + b == inp then zs' else (inp+c):zs' where zs' | a == 26 = zs | otherwise = z:zs runSim :: Sim a -> a -> [(Integer, Integer, Integer)] -> Integer -> [a] runSim s zero steps input = scanl' (\z (step,i) -> s step i z) zero (zip steps (digits input)) ok :: Integer -> Bool ok inp = Just (last (runSim sim 0 vs inp)) == (runALUInt inp (concatMap gen vs) ^. registers . at Z) ok2 :: Integer -> Bool ok2 inp = Just (foldr (\d n -> d + 26*n) 0 (last (runSim sim2 [] vs inp))) == (runALUInt inp (concatMap gen vs) ^. registers . at Z)
b78ee8787b7cc3e21bc3d6a8b5ae8d544dd1c529ea4262689f7bf028fb185809
jacekschae/learn-pedestal-course-files
account.clj
(ns cheffy.account (:require [cheffy.components.auth :as auth] [ring.util.response :as rr] [io.pedestal.http :as http] [io.pedestal.http.body-params :as bp] [cheffy.interceptors :as interceptors] [io.pedestal.interceptor.chain :as chain])) (def sign-up-interceptor {:name ::sign-up-interceptor :enter (fn [{:keys [request] :as ctx}] (let [create-cognito-account (auth/create-cognito-account (:system/auth request) (:transit-params request))] (assoc ctx :tx-data create-cognito-account))) :leave (fn [ctx] (let [account-id (-> ctx :tx-data (first) :account/account-id)] (assoc ctx :response (rr/response {:account-id account-id}))))}) (def sign-up [http/transit-body (bp/body-params) sign-up-interceptor interceptors/transact-interceptor])
null
https://raw.githubusercontent.com/jacekschae/learn-pedestal-course-files/30666cbb8b3662444e16e7fc9ebe65795d7eb7a4/increments/59-confirm-account/src/main/cheffy/account.clj
clojure
(ns cheffy.account (:require [cheffy.components.auth :as auth] [ring.util.response :as rr] [io.pedestal.http :as http] [io.pedestal.http.body-params :as bp] [cheffy.interceptors :as interceptors] [io.pedestal.interceptor.chain :as chain])) (def sign-up-interceptor {:name ::sign-up-interceptor :enter (fn [{:keys [request] :as ctx}] (let [create-cognito-account (auth/create-cognito-account (:system/auth request) (:transit-params request))] (assoc ctx :tx-data create-cognito-account))) :leave (fn [ctx] (let [account-id (-> ctx :tx-data (first) :account/account-id)] (assoc ctx :response (rr/response {:account-id account-id}))))}) (def sign-up [http/transit-body (bp/body-params) sign-up-interceptor interceptors/transact-interceptor])
e03716089b0c24f4e8dd0d5be594d378441806bd6e423bd1cdd6362bca72d86b
epicallan/hreq
HasRequest.hs
| This module provides a ' HasRequest ' class that Interprets -- a 'ReqContent' type level list into 'Request' data -- {-# LANGUAGE PatternSynonyms #-} module Hreq.Core.Client.HasRequest where import Prelude () import Prelude.Compat import Data.Kind import Data.Hlist import Data.Proxy import Data.Singletons import GHC.TypeLits import Data.String (fromString) import Data.String.Conversions (cs) import Data.List (intersperse) import qualified Data.Text as T (concat) import Hreq.Core.API import Hreq.Core.Client.Request import Hreq.Core.Client.BasicAuth import Network.HTTP.Types (QueryItem) pattern Empty :: Hlist '[] pattern Empty = Nil | ' HasRequest ' is used to create a Request from a ' ReqContent ' type level list -- and a 'Verb'. -- @verb@ is requited for obtaining Request method and ' MediaType ' value -- -- @reqComponents@ is a usually a 'ReqContent Type' type level list. -- It can be something else. class HasRequest (reqComponents :: k) (verb :: Type) where type HttpInput reqComponents :: Type httpReq :: Proxy verb -> Proxy reqComponents -> HttpInput reqComponents -> Request -> Request instance ( HttpReqConstraints ts , ReflectMethod method , SingI ('Req ts) , SingI ('Res rs) , HttpResConstraints rs ) => HasRequest (ts :: [ReqContent Type]) (Verb method rs) where type HttpInput ts = Hlist (HttpReq ts) httpReq _ _ input req = let method' = reflectMethod (Proxy @method) acceptHeader = case sing @('Res rs) of SRes ys -> getAcceptHeader ys req' = case sing @('Req ts) of SReq xs -> encodeHlistAsReq xs input req in appendMethod method' $ req' { reqAccept = acceptHeader } getAcceptHeader :: forall (rs :: [ResContent Type]) . HttpResConstraints rs => Sing rs -> Maybe MediaType getAcceptHeader = \case SNil -> Nothing SCons (SResBody sctyp _a) _rs -> Just $ mediaType sctyp SCons (SRaw _) rs -> getAcceptHeader rs SCons (SResHeaders _) rs -> getAcceptHeader rs SCons (SResStatus _ _) rs -> getAcceptHeader rs SCons (SResStream sctyp _) _rs -> Just $ mediaType sctyp | Transform a ' Hlist ' of inputs into a ' Request ' encodeHlistAsReq :: forall (ts :: [ReqContent Type]). (HttpReqConstraints ts) => Sing ts -> Hlist (HttpReq ts) -> Request -> Request encodeHlistAsReq xs input req = case (xs, input) of (SNil, _) -> req (SCons (SPath _ spath) sxs, ys) -> let path = withKnownSymbol spath (cs . symbolVal $ spath) req' = appendToPath path req in encodeHlistAsReq sxs ys req' (SCons (SBasicAuth _ _) sxs, y :. ys) -> let req' = basicAuthReq y req in encodeHlistAsReq sxs ys req' (SCons (SReqHeaders (SCons (STuple2 s _x) hs)) sxs, y :. ys) -> let headerName = fromString $ withKnownSymbol s (symbolVal s) req' = addHeader headerName y req in encodeHlistAsReq (SCons (SReqHeaders hs) sxs) ys req' (SCons (SReqHeaders SNil) sxs, ys) -> encodeHlistAsReq sxs ys req (SCons (SCaptureAll _a) sxs, captureList :. ys) -> let captureFragments = T.concat $ intersperse "/" $ toUrlPiece <$> captureList req' = appendToPath captureFragments req in encodeHlistAsReq sxs ys req' (SCons (SCaptures SNil) sxs, ys) -> encodeHlistAsReq sxs ys req (SCons (SCaptures (SCons _z zs)) sxs, y :. ys) -> let req' = appendToPath (cs $ toUrlPiece y) req in encodeHlistAsReq (SCons (SCaptures zs) sxs) ys req' (SCons (SParams SNil) sxs, ys) -> encodeHlistAsReq sxs ys req (SCons (SParams (SCons (STuple2 s _x) ps)) sxs, y :. ys) -> let req' = appendToQueryString (createParam s y) req in encodeHlistAsReq (SCons (SParams ps) sxs) ys req' (SCons (SQueryFlags _a sflags) SNil, _) -> appendQueryFlags (toQueryFlags sflags) req (SCons (SQueryFlags _a sflags) sxs, ys) -> encodeHlistAsReq sxs ys $ appendQueryFlags (toQueryFlags sflags) req (SCons (SReqBody sctyp _sa) sxs, y :. ys) -> let body = RequestBodyLBS $ mediaEncode sctyp y req' = setReqBody body (mediaType sctyp) req in encodeHlistAsReq sxs ys req' (SCons (SStreamBody sctyp _sa) sxs, y :. ys) -> let body = RequestBodyStream $ givePopper y req' = setReqBody body (mediaType sctyp) req in encodeHlistAsReq sxs ys req' {------------------------------------------------------------------------------- Helper functions -------------------------------------------------------------------------------} createParam :: (KnownSymbol p, ToHttpApiData a) => Sing p -> a -> QueryItem createParam sname val = let pname = withKnownSymbol sname (symbolVal sname) value = toQueryParam val in (cs pname, Just $ cs value) appendQueryFlags :: [String] -> Request -> Request appendQueryFlags xs req = let queryflags = (\ x -> (cs x, Nothing)) <$> xs in foldr appendToQueryString req queryflags toQueryFlags :: forall (fs :: [Symbol]) . All KnownSymbol fs => Sing fs -> [String] toQueryFlags = \case SNil -> [] SCons x xs -> withKnownSymbol x (symbolVal x) : toQueryFlags xs
null
https://raw.githubusercontent.com/epicallan/hreq/f12fcb9b9dd1ad903c6b36a8cf850edb213d4792/hreq-core/src/Hreq/Core/Client/HasRequest.hs
haskell
a 'ReqContent' type level list into 'Request' data # LANGUAGE PatternSynonyms # and a 'Verb'. @reqComponents@ is a usually a 'ReqContent Type' type level list. It can be something else. ------------------------------------------------------------------------------ Helper functions ------------------------------------------------------------------------------
| This module provides a ' HasRequest ' class that Interprets module Hreq.Core.Client.HasRequest where import Prelude () import Prelude.Compat import Data.Kind import Data.Hlist import Data.Proxy import Data.Singletons import GHC.TypeLits import Data.String (fromString) import Data.String.Conversions (cs) import Data.List (intersperse) import qualified Data.Text as T (concat) import Hreq.Core.API import Hreq.Core.Client.Request import Hreq.Core.Client.BasicAuth import Network.HTTP.Types (QueryItem) pattern Empty :: Hlist '[] pattern Empty = Nil | ' HasRequest ' is used to create a Request from a ' ReqContent ' type level list @verb@ is requited for obtaining Request method and ' MediaType ' value class HasRequest (reqComponents :: k) (verb :: Type) where type HttpInput reqComponents :: Type httpReq :: Proxy verb -> Proxy reqComponents -> HttpInput reqComponents -> Request -> Request instance ( HttpReqConstraints ts , ReflectMethod method , SingI ('Req ts) , SingI ('Res rs) , HttpResConstraints rs ) => HasRequest (ts :: [ReqContent Type]) (Verb method rs) where type HttpInput ts = Hlist (HttpReq ts) httpReq _ _ input req = let method' = reflectMethod (Proxy @method) acceptHeader = case sing @('Res rs) of SRes ys -> getAcceptHeader ys req' = case sing @('Req ts) of SReq xs -> encodeHlistAsReq xs input req in appendMethod method' $ req' { reqAccept = acceptHeader } getAcceptHeader :: forall (rs :: [ResContent Type]) . HttpResConstraints rs => Sing rs -> Maybe MediaType getAcceptHeader = \case SNil -> Nothing SCons (SResBody sctyp _a) _rs -> Just $ mediaType sctyp SCons (SRaw _) rs -> getAcceptHeader rs SCons (SResHeaders _) rs -> getAcceptHeader rs SCons (SResStatus _ _) rs -> getAcceptHeader rs SCons (SResStream sctyp _) _rs -> Just $ mediaType sctyp | Transform a ' Hlist ' of inputs into a ' Request ' encodeHlistAsReq :: forall (ts :: [ReqContent Type]). (HttpReqConstraints ts) => Sing ts -> Hlist (HttpReq ts) -> Request -> Request encodeHlistAsReq xs input req = case (xs, input) of (SNil, _) -> req (SCons (SPath _ spath) sxs, ys) -> let path = withKnownSymbol spath (cs . symbolVal $ spath) req' = appendToPath path req in encodeHlistAsReq sxs ys req' (SCons (SBasicAuth _ _) sxs, y :. ys) -> let req' = basicAuthReq y req in encodeHlistAsReq sxs ys req' (SCons (SReqHeaders (SCons (STuple2 s _x) hs)) sxs, y :. ys) -> let headerName = fromString $ withKnownSymbol s (symbolVal s) req' = addHeader headerName y req in encodeHlistAsReq (SCons (SReqHeaders hs) sxs) ys req' (SCons (SReqHeaders SNil) sxs, ys) -> encodeHlistAsReq sxs ys req (SCons (SCaptureAll _a) sxs, captureList :. ys) -> let captureFragments = T.concat $ intersperse "/" $ toUrlPiece <$> captureList req' = appendToPath captureFragments req in encodeHlistAsReq sxs ys req' (SCons (SCaptures SNil) sxs, ys) -> encodeHlistAsReq sxs ys req (SCons (SCaptures (SCons _z zs)) sxs, y :. ys) -> let req' = appendToPath (cs $ toUrlPiece y) req in encodeHlistAsReq (SCons (SCaptures zs) sxs) ys req' (SCons (SParams SNil) sxs, ys) -> encodeHlistAsReq sxs ys req (SCons (SParams (SCons (STuple2 s _x) ps)) sxs, y :. ys) -> let req' = appendToQueryString (createParam s y) req in encodeHlistAsReq (SCons (SParams ps) sxs) ys req' (SCons (SQueryFlags _a sflags) SNil, _) -> appendQueryFlags (toQueryFlags sflags) req (SCons (SQueryFlags _a sflags) sxs, ys) -> encodeHlistAsReq sxs ys $ appendQueryFlags (toQueryFlags sflags) req (SCons (SReqBody sctyp _sa) sxs, y :. ys) -> let body = RequestBodyLBS $ mediaEncode sctyp y req' = setReqBody body (mediaType sctyp) req in encodeHlistAsReq sxs ys req' (SCons (SStreamBody sctyp _sa) sxs, y :. ys) -> let body = RequestBodyStream $ givePopper y req' = setReqBody body (mediaType sctyp) req in encodeHlistAsReq sxs ys req' createParam :: (KnownSymbol p, ToHttpApiData a) => Sing p -> a -> QueryItem createParam sname val = let pname = withKnownSymbol sname (symbolVal sname) value = toQueryParam val in (cs pname, Just $ cs value) appendQueryFlags :: [String] -> Request -> Request appendQueryFlags xs req = let queryflags = (\ x -> (cs x, Nothing)) <$> xs in foldr appendToQueryString req queryflags toQueryFlags :: forall (fs :: [Symbol]) . All KnownSymbol fs => Sing fs -> [String] toQueryFlags = \case SNil -> [] SCons x xs -> withKnownSymbol x (symbolVal x) : toQueryFlags xs
a9e399bba8a7d65157bc24cc8cb5e0ac6b72ec80fa982b95989f7f77cf8990e8
erlang/otp
asn1_SUITE.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2001 - 2022 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% Purpose : Test suite for the ASN.1 application -module(asn1_SUITE). %% Suppress compilation of an addititional module compiled for maps. -define(NO_MAPS_MODULE, asn1_test_lib_no_maps). -define(only_ber(Func), if Rule =:= ber -> Func; true -> ok end). -compile(export_all). -include_lib("common_test/include/ct.hrl"). %%------------------------------------------------------------------------------ %% Suite definition %%------------------------------------------------------------------------------ suite() -> [{ct_hooks, [ts_install_cth]}, {timetrap,{minutes,60}}]. all() -> [xref, xref_export_all, c_string, constraint_equivalence, ber_decode_invalid_length, ber_choiceinseq, ber_optional, tagdefault_automatic, cover, parse, test_undecoded_rest, specialized_decodes, special_decode_performance, testMegaco, testConstraints, testCompactBitString, default, testPrim, rtUI, testPrimStrings, per, ber, der, h323test, testExtensibilityImplied, testChoice, testDefaultOctetString, testMultipleLevels, testOpt, testSeqDefault, testMaps, testTypeValueNotation, testExternal, testSeqExtension, testSeqOptional, testSeqPrim, testSeqTypeRefCho, testSeqTypeRefPrim, testSeqTypeRefSeq, testSeqTypeRefSet, testSeqOf, testSeqOfIndefinite, testSeqOfCho, testSeqOfChoExt, testExtensionAdditionGroup, testSet, testSetOf, testEnumExt, value_test, testSeq2738, constructed, ber_decode_error, otp_14440, testSeqSetIndefinite, testChoiceIndefinite, per_open_type, testInfObjectClass, testUniqueObjectSets, testInfObjExtract, testParam, testFragmented, testMergeCompile, testobj, testDeepTConstr, testImport, testDER, testDEFAULT, testExtensionDefault, testMvrasn6, testContextSwitchingTypes, testOpenTypeImplicitTag, testROSE, testINSTANCE_OF, testTCAP, test_ParamTypeInfObj, test_Defed_ObjectIdentifier, testSelectionType, testSSLspecs, testNortel, test_WS_ParamClass, test_modified_x420, %% Some heavy tests. testTcapsystem, testNBAPsystem, testS1AP, testRfcs, test_compile_options, testDoubleEllipses, test_x691, ticket_6143, test_OTP_9688, testValueTest, testComment, testName2Number, ticket_7407, ticket7904, {group, performance}]. groups() -> [{performance, [], [testTimer_ber, testTimer_ber_maps, testTimer_per, testTimer_per_maps, testTimer_uper, testTimer_uper_maps]}]. %%------------------------------------------------------------------------------ Init / end %%------------------------------------------------------------------------------ init_per_suite(Config) -> Config. end_per_suite(_Config) -> ok. init_per_group(_GroupName, Config) -> Config. end_per_group(_GroupName, Config) -> Config. init_per_testcase(Func, Config) -> CaseDir = filename:join(proplists:get_value(priv_dir, Config), Func), ok = filelib:ensure_dir(filename:join([CaseDir, dummy_file])), true = code:add_patha(CaseDir), [{case_dir, CaseDir}|Config]. end_per_testcase(_Func, Config) -> CaseDir = proplists:get_value(case_dir, Config), asn1_test_lib:rm_dirs([CaseDir]), code:del_path(CaseDir). %%------------------------------------------------------------------------------ %% Test runners %%------------------------------------------------------------------------------ have_jsonlib() -> case code:which(jsx) of non_existing -> false; _ -> true end. test(Config, TestF) -> TestJer = case have_jsonlib() of true -> [jer]; false -> [] end, test(Config, TestF, [per, uper, ber] ++ TestJer), case TestJer of [] -> {comment,"skipped JER"}; _ -> ok end. test(Config, TestF, Rules) -> Fun = fun(C, R, O) -> M = element(2, erlang:fun_info(TestF, module)), F = element(2, erlang:fun_info(TestF, name)), io:format("Running ~p:~p with ~p...~n", [M, F, {R, O}]), try TestF(C, R, O) catch Class:Reason:Stk -> NewReason = {Reason, [{rule, R}, {options, O}]}, erlang:raise(Class, NewReason, Stk) end end, Result = [run_case(Config, Fun, rule(Rule), opts(Rule)) || Rule <- Rules], case lists:usort(Result) of At least one test ran Skips -> {skip, [R || {skip, R} <- Skips]} % All skipped end. rule(A) when is_atom(A) -> A; rule({A, _Opts} ) -> A. opts(Rule) when is_atom(Rule) -> []; opts({_Rule, Opts}) -> Opts. run_case(Config, Fun, Rule, Opts) -> CaseDir = proplists:get_value(case_dir, Config), Dir = filename:join([CaseDir, join(Rule, Opts)]), ok = filelib:ensure_dir(filename:join([Dir, dummy_file])), replace_path(CaseDir, Dir), NewConfig = lists:keyreplace(case_dir, 1, Config, {case_dir, Dir}), % Run the actual test function Result = Fun(NewConfig, Rule, Opts), replace_path(Dir, CaseDir), case Result of {skip, _Reason} -> Result; _ -> true end. replace_path(PathA, PathB) -> true = code:del_path(PathA), true = code:add_patha(PathB). join(Rule, Opts) -> lists:join("_", [atom_to_list(Rule)|lists:map(fun atom_to_list/1, Opts)]). %%------------------------------------------------------------------------------ %% Test cases %%------------------------------------------------------------------------------ Cover run - time functions that are only called by the ASN.1 compiler %% (if any). cover(_) -> Wc = filename:join([code:lib_dir(asn1),"ebin","asn1ct_eval_*.beam"]), Beams = filelib:wildcard(Wc), true = Beams =/= [], [begin M0 = filename:basename(Beam), M1 = filename:rootname(M0), M = list_to_atom(M1), "asn1ct_eval_" ++ Group0 = M1, Group = list_to_atom(Group0), io:format("%%\n" "%% ~s\n" "%%\n", [M]), asn1ct_func:start_link(), [asn1ct_func:need({Group,F,A}) || {F,A} <- M:module_info(exports), F =/= module_info], asn1ct_func:generate(group_leader()) end || Beam <- Beams], ok. testPrim(Config) -> test(Config, fun testPrim/3). testPrim(Config, Rule, Opts) -> Files = ["Prim","Real"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), do_test_prim(Rule, false), asn1_test_lib:compile_all(Files, Config, [no_ok_wrapper,Rule|Opts]), do_test_prim(Rule, true). do_test_prim(Rule, NoOkWrapper) -> io:format("No ok wrapper: ~p\n", [NoOkWrapper]), put(no_ok_wrapper, NoOkWrapper), testPrim:bool(Rule), testPrim:int(Rule), testPrim:enum(Rule), testPrim:obj_id(Rule), testPrim:rel_oid(Rule), testPrim:null(Rule), Temporary workaround for JER testCompactBitString(Config) -> test(Config, fun testCompactBitString/3). testCompactBitString(Config, Rule, Opts) -> Files = ["PrimStrings", "Constraints"], asn1_test_lib:compile_all(Files, Config, [Rule, compact_bit_string|Opts]), testCompactBitString:compact_bit_string(Rule), testCompactBitString:bit_string_unnamed(Rule), testCompactBitString:bit_string_unnamed(Rule), testCompactBitString:ticket_7734(Rule), testCompactBitString:otp_4869(Rule). testPrimStrings(Config) -> test(Config, fun testPrimStrings/3, [ber,{ber,[der]},per,uper]). testPrimStrings(Config, Rule, Opts) -> LegacyOpts = [legacy_erlang_types|Opts], Files = ["PrimStrings", "BitStr"], asn1_test_lib:compile_all(Files, Config, [Rule|LegacyOpts]), testPrimStrings_cases(Rule, LegacyOpts), asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testPrimStrings_cases(Rule, Opts), asn1_test_lib:compile_all(Files, Config, [legacy_bit_string,Rule|Opts]), testPrimStrings:bit_string(Rule, Opts), asn1_test_lib:compile_all(Files, Config, [compact_bit_string,Rule|Opts]), testPrimStrings:bit_string(Rule, Opts), testPrimStrings:more_strings(Rule). testPrimStrings_cases(Rule, Opts) -> testPrimStrings:bit_string(Rule, Opts), testPrimStrings:octet_string(Rule), testPrimStrings:numeric_string(Rule), testPrimStrings:other_strings(Rule), testPrimStrings:universal_string(Rule), testPrimStrings:bmp_string(Rule), testPrimStrings:times(Rule), testPrimStrings:utf8_string(Rule), testPrimStrings:fragmented(Rule). testExternal(Config) -> test(Config, fun testExternal/3). testExternal(Config, Rule, Opts) -> asn1_test_lib:compile_all(["External", "ChoExternal", "PrimExternal", "SeqExternal", "SeqOfExternal", "SeqOfTag", "SeqTag", "SetExtension", "SetExternal", "SetOfExternal", "SetOfTag", "SetTag"], Config, [Rule|Opts]), testChoExternal:external(Rule), testPrimExternal:external(Rule), testSeqExternal:main(Rule), testSeqOfExternal:main(Rule), testSeqOfTag:main(Rule), testSeqTag:main(Rule), testSetExtension:main(Rule), testSetExternal:main(Rule), testSetOfExternal:main(Rule), testSetOfTag:main(Rule), testSetTag:main(Rule). testExtensibilityImplied(Config) -> test(Config, fun testExtensibilityImplied/3). testExtensibilityImplied(Config, Rule, Opts) -> asn1_test_lib:compile("ExtensibilityImplied", Config, [Rule,no_ok_wrapper|Opts]), testExtensibilityImplied:main(Rule). testChoice(Config) -> test(Config, fun testChoice/3). testChoice(Config, Rule, Opts) -> Files = ["ChoPrim", "ChoExtension", "ChoOptional", "ChoOptionalImplicitTag", "ChoRecursive", "ChoTypeRefCho", "ChoTypeRefPrim", "ChoTypeRefSeq", "ChoTypeRefSet"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testChoPrim:bool(Rule), testChoPrim:int(Rule), testChoExtension:extension(Rule), testChoOptional:run(), testChoRecursive:recursive(Rule), testChoTypeRefCho:choice(Rule), testChoTypeRefPrim:prim(Rule), testChoTypeRefSeq:seq(Rule), testChoTypeRefSet:set(Rule). testDefaultOctetString(Config) -> test(Config, fun testDefaultOctetString/3). testDefaultOctetString(Config, Rule, Opts) -> asn1_test_lib:compile("DefaultOctetString", Config, [Rule|Opts]), testDefaultOctetString:dos(Rule). testMultipleLevels(Config) -> test(Config, fun testMultipleLevels/3). testMultipleLevels(Config, Rule, Opts) -> asn1_test_lib:compile("MultipleLevels", Config, [Rule|Opts]), testMultipleLevels:main(Rule). testDEFAULT(Config) -> test(Config, fun testDEFAULT/3, [ber,{ber,[der]},per,uper]). testDEFAULT(Config, Rule, Opts) -> asn1_test_lib:compile_all(["Def","Default"], Config, [Rule|Opts]), testDef:main(Rule), testSeqSetDefaultVal:main(Rule, Opts), asn1_test_lib:compile_all(["Def","Default"], Config, [legacy_erlang_types,Rule|Opts]), testDef:main(Rule), testSeqSetDefaultVal:main(Rule, Opts). testExtensionDefault(Config) -> test(Config, fun testExtensionDefault/3). testExtensionDefault(Config, Rule, Opts) -> asn1_test_lib:compile_all(["ExtensionDefault"], Config, [Rule|Opts]), testExtensionDefault:main(Rule). testMaps(Config) -> Jer = case have_jsonlib() of true -> [{jer,[maps,no_ok_wrapper]}]; false -> [] end, RulesAndOptions = [{ber,[maps,no_ok_wrapper]}, {ber,[maps,der,no_ok_wrapper]}, {per,[maps,no_ok_wrapper]}, {uper,[maps,no_ok_wrapper]}] ++ Jer, test(Config, fun testMaps/3, RulesAndOptions), case Jer of [] -> {comment,"skipped JER"}; _ -> ok end. testMaps(Config, Rule, Opts) -> asn1_test_lib:compile_all(['Maps'], Config, [Rule|Opts]), testMaps:main(Rule). testOpt(Config) -> test(Config, fun testOpt/3). testOpt(Config, Rule, Opts) -> asn1_test_lib:compile("Opt", Config, [Rule|Opts]), testOpt:main(Rule). testEnumExt(Config) -> test(Config, fun testEnumExt/3). testEnumExt(Config, Rule, Opts) -> asn1_test_lib:compile("EnumExt", Config, [Rule|Opts]), testEnumExt:main(Rule). %% Test of OTP-2523 ENUMERATED with extensionmark. testSeqDefault(Config) -> test(Config, fun testSeqDefault/3). testSeqDefault(Config, Rule, Opts) -> asn1_test_lib:compile("SeqDefault", Config, [Rule|Opts]), testSeqDefault:main(Rule). testSeqExtension(Config) -> test(Config, fun testSeqExtension/3, [ber,uper]). testSeqExtension(Config, Rule, Opts) -> asn1_test_lib:compile_all(["External", "SeqExtension", "SeqExtension2"], Config, [Rule|Opts]), DataDir = proplists:get_value(data_dir, Config), testSeqExtension:main(Rule, DataDir, [Rule|Opts]). testSeqOptional(Config) -> test(Config, fun testSeqOptional/3). testSeqOptional(Config, Rule, Opts) -> asn1_test_lib:compile("SeqOptional", Config, [Rule|Opts]), testSeqOptional:main(Rule). testSeqPrim(Config) -> test(Config, fun testSeqPrim/3). testSeqPrim(Config, Rule, Opts) -> asn1_test_lib:compile("SeqPrim", Config, [Rule|Opts]), testSeqPrim:main(Rule). %% Test of OTP-2738 Detect corrupt optional component. testSeq2738(Config) -> test(Config, fun testSeq2738/3). testSeq2738(Config, Rule, Opts) -> asn1_test_lib:compile("Seq2738", Config, [Rule|Opts]), testSeq2738:main(Rule). testSeqTypeRefCho(Config) -> test(Config, fun testSeqTypeRefCho/3). testSeqTypeRefCho(Config, Rule, Opts) -> asn1_test_lib:compile("SeqTypeRefCho", Config, [Rule|Opts]), testSeqTypeRefCho:main(Rule). testSeqTypeRefPrim(Config) -> test(Config, fun testSeqTypeRefPrim/3). testSeqTypeRefPrim(Config, Rule, Opts) -> asn1_test_lib:compile("SeqTypeRefPrim", Config, [Rule|Opts]), testSeqTypeRefPrim:main(Rule). testSeqTypeRefSeq(Config) -> test(Config, fun testSeqTypeRefSeq/3). testSeqTypeRefSeq(Config, Rule, Opts) -> asn1_test_lib:compile("SeqTypeRefSeq", Config, [Rule|Opts]), testSeqTypeRefSeq:main(Rule). testSeqTypeRefSet(Config) -> test(Config, fun testSeqTypeRefSet/3). testSeqTypeRefSet(Config, Rule, Opts) -> asn1_test_lib:compile("SeqTypeRefSet", Config, [Rule|Opts]), testSeqTypeRefSet:main(Rule). testSeqOf(Config) -> test(Config, fun testSeqOf/3). testSeqOf(Config, Rule, Opts) -> asn1_test_lib:compile_all(["SeqOf", "SeqOfEnum", "XSeqOf"], Config, [Rule|Opts]), testSeqOf:main(Rule). testSeqOfCho(Config) -> test(Config, fun testSeqOfCho/3). testSeqOfCho(Config, Rule, Opts) -> asn1_test_lib:compile("SeqOfCho", Config, [Rule|Opts]), testSeqOfCho:main(Rule). testSeqOfChoExt(Config) -> test(Config, fun testSeqOfChoExt/3). testSeqOfChoExt(Config, Rule, Opts) -> asn1_test_lib:compile("SeqOfChoExt", Config, [Rule|Opts]), testSeqOfChoExt:main(Rule). testSeqOfIndefinite(Config) -> test(Config, fun testSeqOfIndefinite/3, [ber]). testSeqOfIndefinite(Config, Rule, Opts) -> Files = ["Mvrasn-Constants-1", "Mvrasn-DataTypes-1", "Mvrasn-21-4", "Mvrasn-20-4", "Mvrasn-19-4", "Mvrasn-18-4", "Mvrasn-17-4", "Mvrasn-15-4", "Mvrasn-14-4", "Mvrasn-11-4", "SeqOf"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testSeqOfIndefinite:main(). testSet(Config) -> test(Config, fun testSet/3). testSet(Config, Rule, Opts) -> Files = ["SetDefault", "SetOptional", "SetPrim", "SetTypeRefCho", "SetTypeRefPrim", "SetTypeRefSeq", "SetTypeRefSet"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testSetDefault:main(Rule), testSetOptional:ticket_7533(Rule), testSetOptional:main(Rule), testSetPrim:main(Rule), testSetTypeRefCho:main(Rule), testSetTypeRefPrim:main(Rule), testSetTypeRefSeq:main(Rule), testSetTypeRefSet:main(Rule). testSetOf(Config) -> test(Config, fun testSetOf/3). testSetOf(Config, Rule, Opts) -> Files = ["SetOf", "SetOfCho"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testSetOf:main(Rule), testSetOfCho:main(Rule). c_string(Config) -> test(Config, fun c_string/3). c_string(Config, Rule, Opts) -> asn1_test_lib:compile("String", Config, [Rule|Opts]), asn1ct:test('String'). constraint_equivalence(Config) -> constraint_equivalence_abs(Config), test(Config, fun constraint_equivalence/3). constraint_equivalence(Config, Rule, Opts) -> M = 'ConstraintEquivalence', asn1_test_lib:compile(M, Config, [Rule|Opts]). constraint_equivalence_abs(Config) -> DataDir = proplists:get_value(data_dir, Config), CaseDir = proplists:get_value(case_dir, Config), Asn1Spec = "ConstraintEquivalence", Asn1Src = filename:join(DataDir, Asn1Spec), ok = asn1ct:compile(Asn1Src, [abs,{outdir,CaseDir}]), AbsFile = filename:join(CaseDir, Asn1Spec++".abs"), {ok,Terms} = file:consult(AbsFile), Cs = [begin Constraints = element(4, Type), Name1 = atom_to_list(Name0), {Name,_} = lists:splitwith(fun(C) -> C =/= $X end, Name1), {Name,Constraints} end || {typedef,_,_,Name0,Type} <- Terms], R = sofs:relation(Cs, [{name,constraint}]), F0 = sofs:relation_to_family(R), F = sofs:to_external(F0), Diff = [E || {_,L}=E <- F, length(L) > 1], case Diff of [] -> ok; [_|_] -> io:put_chars("Not equivalent:\n"), [io:format("~s: ~p\n", [N,D]) || {N,D} <- Diff], ct:fail(length(Diff)) end. parse(Config) -> [asn1_test_lib:compile(M, Config, [abs]) || M <- test_modules()]. per(Config) -> test(Config, fun per/3, [per,uper,{per,[maps]},{uper,[maps]}]). per(Config, Rule, Opts) -> module_test(per_modules(), Config, Rule, Opts). ber(Config) -> test(Config, fun ber/3, [ber,{ber,[maps]}]). ber(Config, Rule, Opts) -> module_test(ber_modules(), Config, Rule, Opts). der(Config) -> asn1_test_lib:compile_all(ber_modules(), Config, [der]). module_test(Modules, Config, Rule, Opts) -> asn1_test_lib:compile_all(Modules, Config, [Rule,?NO_MAPS_MODULE|Opts]), _ = [do_module_test(M, Config, Opts) || M <- Modules], ok. do_module_test(M0, Config, Opts) -> case list_to_atom(M0) of 'LDAP' -> %% Because of the recursive definition of 'Filter' in %% the LDAP module, the construction of a sample %% value for 'Filter' is not guaranteed to terminate. ok; M -> TestOpts = [{i, proplists:get_value(case_dir, Config)}], case asn1ct:test(M, TestOpts) of ok -> ok; Error -> erlang:error({test_failed, M, Opts, Error}) end end. ber_decode_invalid_length(_Config) -> Bin = <<48,129,157,48,0,2,1,2,164,0,48,129,154,49,24,48,22,6, 3,85,4,10,19,15,69,120,97,109,112,108,101,32,67,111, 109,112,97,110,121,49,29,48,27,6,9,42,134,72,134,247, 13,1,9,1,22,14,99,97,64,101,120,97,109,112,108,101,46, 99,111,109,49,13,48,11,6,3,85,4,7,19,4,79,117,108,117, 49,26,48,24,6,3,85,4,8,19,17,80,111,104,106,111,105, 115,45,80,111,104,106,97,110,109,97,97,49,11,48,9,6,3, 85,4,6,19,2,70,73,49,19,48,17,6,3,85,4,3,19,10,69,120, 97,109,112,108,101,32,67,65,49,11,48,16,6,3,85,4,11, 19,9,84,101>>, {'EXIT',{error,{asn1,{invalid_value,12}}}} = (catch asn1rt_nif:decode_ber_tlv(Bin)), ok. ber_choiceinseq(Config) -> test(Config, fun ber_choiceinseq/3, [ber]). ber_choiceinseq(Config, Rule, Opts) -> asn1_test_lib:compile("ChoiceInSeq", Config, [Rule|Opts]). ber_optional(Config) -> test(Config, fun ber_optional/3, [ber]). ber_optional(Config, Rule, Opts) -> asn1_test_lib:compile("SOpttest", Config, [Rule|Opts]), V = {'S', {'A', 10, asn1_NOVALUE, asn1_NOVALUE}, {'B', asn1_NOVALUE, asn1_NOVALUE, asn1_NOVALUE}, {'C', asn1_NOVALUE, 111, asn1_NOVALUE}}, asn1_test_lib:roundtrip('SOpttest', 'S', V). tagdefault_automatic(Config) -> test(Config, fun tagdefault_automatic/3, [ber]). tagdefault_automatic(Config, Rule, Opts) -> asn1_test_lib:compile("TAGDEFAULT-AUTOMATIC", Config, [Rule|Opts]), << 48,8,128,2,100,101,129,2,110,111 >> = asn1_test_lib:roundtrip_enc('TAGDEFAULT-AUTOMATIC', 'Tagged', {'Tagged', << 100,101 >>, << 110,111 >>}), << 48,8,128,2,100,101,129,2,110,111 >> = asn1_test_lib:roundtrip_enc('TAGDEFAULT-AUTOMATIC', 'Untagged', {'Untagged', << 100,101 >>, << 110,111 >>}), << 48,8,4,2,100,101,130,2,110,111 >> = asn1_test_lib:roundtrip_enc('TAGDEFAULT-AUTOMATIC', 'Mixed', {'Mixed', << 100,101 >>, << 110,111 >>}), ok. %% records used by test-case default -record('Def1', {bool0, bool1 = asn1_DEFAULT, bool2 = asn1_DEFAULT, bool3 = asn1_DEFAULT}). default(Config) -> test(Config, fun default/3). default(Config, Rule, Opts) -> asn1_test_lib:compile("Def", Config, [Rule|Opts]), asn1_test_lib:roundtrip('Def', 'Def1', #'Def1'{bool0=true}, #'Def1'{bool0=true,bool1=false, bool2=false,bool3=false}), asn1_test_lib:roundtrip('Def', 'Def1', #'Def1'{bool0=true,bool2=false}, #'Def1'{bool0=true,bool1=false, bool2=false,bool3=false}). value_test(Config) -> test(Config, fun value_test/3). value_test(Config, Rule, Opts) -> asn1_test_lib:compile("ObjIdValues", Config, [Rule|Opts]), {ok, _} = asn1ct:test('ObjIdValues', 'ObjIdType', 'ObjIdValues':'mobileDomainId'()). constructed(Config) -> test(Config, fun constructed/3, [ber]). constructed(Config, Rule, Opts) -> asn1_test_lib:compile("Constructed", Config, [Rule|Opts]), <<40,3,1,1,0>> = asn1_test_lib:roundtrip_enc('Constructed', 'S', {'S',false}), <<40,5,48,3,1,1,0>> = asn1_test_lib:roundtrip_enc('Constructed', 'S2', {'S2',false}), <<136,1,10>> = asn1_test_lib:roundtrip_enc('Constructed', 'I', 10), ok. ber_decode_error(Config) -> test(Config, fun ber_decode_error/3, [ber]). ber_decode_error(Config, Rule, Opts) -> asn1_test_lib:compile("Constructed", Config, [Rule|Opts]), ber_decode_error:run(Opts). otp_14440(_Config) -> {ok, Peer, N} = ?CT_PEER(), Result = rpc:call(N, ?MODULE, otp_14440_decode, []), io:format("Decode result = ~p~n", [Result]), peer:stop(Peer), case Result of {exit,{error,{asn1,{invalid_value,5}}}} -> ok; %% We get this if stack depth limit kicks in: {exit,{error,{asn1,{unknown,_}}}} -> ok; _ -> ct:fail(Result) end. %% otp_14440_decode() -> Data = iolist_to_binary( lists:duplicate( 32, list_to_binary(lists:duplicate(1024, 16#7f)))), try asn1rt_nif:decode_ber_tlv(Data) of Result -> {unexpected_return,Result} catch Class:Reason -> {Class,Reason} end. h323test(Config) -> test(Config, fun h323test/3). h323test(Config, Rule, Opts) -> Files = ["H235-SECURITY-MESSAGES", "H323-MESSAGES", "MULTIMEDIA-SYSTEM-CONTROL"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), h323test:run(Rule). per_open_type(Config) -> test(Config, fun per_open_type/3, [per]). per_open_type(Config, Rule, Opts) -> asn1_test_lib:compile("OpenType", Config, [Rule|Opts]), {ok, _} = asn1ct:test('OpenType', 'Ot', {'Stype', 10, true}). testConstraints(Config) -> test(Config, fun testConstraints/3). testConstraints(Config, Rule, Opts) -> Files = ["Constraints", "LargeConstraints"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testConstraints:int_constraints(Rule), case Rule of ber -> ok; jer -> ok; % subtype constraint is not checked _ -> testConstraints:refed_NNL_name(Rule) end. testSeqSetIndefinite(Config) -> test(Config, fun testSeqSetIndefinite/3, [ber]). testSeqSetIndefinite(Config, Rule, Opts) -> asn1_test_lib:compile("SeqSetIndefinite", Config, [Rule|Opts]), testSeqSetIndefinite:main(). testChoiceIndefinite(Config) -> test(Config, fun testChoiceIndefinite/3, [ber]). testChoiceIndefinite(Config, Rule, Opts) -> asn1_test_lib:compile("ChoiceIndef", Config, [Rule|Opts]), testChoiceIndefinite:main(Rule). testInfObjectClass(Config) -> test(Config, fun testInfObjectClass/3). testInfObjectClass(Config, Rule, Opts) -> Files = ["ErrorClass", "InfClass"], InfObjFiles = ["RANAPextract1", "InfObj", "MAP-ExtensionDataTypes", "Objects", "INAPv2extract"], RANAPFiles = ["RANAP-CommonDataTypes", "RANAP-Constants", "RANAP-Containers", "RANAP-IEs", "RANAP-PDU-Contents", "RANAP-PDU-Descriptions"], asn1_test_lib:compile_all(Files ++ InfObjFiles ++ RANAPFiles, Config, [Rule|Opts]), testInfObjectClass:main(Rule), testInfObj:main(Rule). testUniqueObjectSets(Config) -> test(Config, fun testUniqueObjectSets/3). testUniqueObjectSets(Config, Rule, Opts) -> CaseDir = proplists:get_value(case_dir, Config), testUniqueObjectSets:main(CaseDir, Rule, Opts). testInfObjExtract(Config) -> test(Config, fun testInfObjExtract/3). testInfObjExtract(Config, Rule, Opts) -> asn1_test_lib:compile("InfObjExtract", Config, [Rule|Opts]), testInfObjExtract:main(Rule). testParam(Config) -> test(Config, fun testParam/3, [ber,{ber,[der]},per,uper]). testParam(Config, Rule, Opts) -> Files = ["ParamBasic","Param","Param2"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testParamBasic:main(Rule), testParameterizedInfObj:main(Config, Rule), asn1_test_lib:compile("Param", Config, [legacy_erlang_types,Rule|Opts]), testParameterizedInfObj:param(Rule). testFragmented(Config) -> test(Config, fun testFragmented/3). testFragmented(Config, Rule, Opts) -> asn1_test_lib:compile("Fragmented", Config, [Rule|Opts]), testFragmented:main(Rule). testMergeCompile(Config) -> test(Config, fun testMergeCompile/3). testMergeCompile(Config, Rule, Opts) -> Files = ["MS.set.asn", "RANAPSET.set.asn1", "Mvrasn4.set.asn", "Mvrasn6.set.asn"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testMergeCompile:main(Rule), testMergeCompile:mvrasn(Rule). testobj(Config) -> test(Config, fun testobj/3). testobj(_Config, jer, _Opts) -> ok; testobj(Config, Rule, Opts) -> asn1_test_lib:compile("RANAP", Config, [legacy_erlang_types, Rule|Opts]), asn1_test_lib:compile_erlang("testobj", Config, []), ok = testobj:run(), ok = testParameterizedInfObj:ranap(Rule). testDeepTConstr(Config) -> test(Config, fun testDeepTConstr/3). testDeepTConstr(Config, Rule, Opts) -> asn1_test_lib:compile_all(["TConstrChoice", "TConstr"], Config, [Rule|Opts]), testDeepTConstr:main(Rule). testImport(Config) -> test(Config, fun testImport/3). testImport(Config, Rule, Opts) -> Files = ["ImportsFrom","ImportsFrom2","ImportsFrom3", "Importing","Exporting"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), 42 = 'ImportsFrom':i(), testImporting:main(Rule), ok. testMegaco(Config) -> test(Config, fun testMegaco/3). testMegaco(Config, Rule, Opts) -> {ok, Module1, Module2} = testMegaco:compile(Config, Rule, [legacy_erlang_types|Opts]), ok = testMegaco:main(Module1, Config), ok = testMegaco:main(Module2, Config). testMvrasn6(Config) -> test(Config, fun testMvrasn6/3). testMvrasn6(Config, Rule, Opts) -> asn1_test_lib:compile_all(["Mvrasn-21-4", "Mvrasn-20-6", "Mvrasn-19-6", "Mvrasn-15-6", "Mvrasn-18-6", "Mvrasn-14-6", "Mvrasn-11-6"], Config, [Rule|Opts]). testContextSwitchingTypes(Config) -> test(Config, fun testContextSwitchingTypes/3). testContextSwitchingTypes(Config, Rule, Opts) -> asn1_test_lib:compile("ContextSwitchingTypes", Config, [Rule|Opts]), testContextSwitchingTypes:test(Rule,Config). testTypeValueNotation(Config) -> test(Config, fun testTypeValueNotation/3). testTypeValueNotation(Config, Rule, Opts) -> asn1_test_lib:compile("SeqTypeRefPrim", Config, [Rule|Opts]), testTypeValueNotation:main(Rule, Opts). testValueTest(Config) -> test(Config, fun testValueTest/3). testValueTest(Config, Rule, Opts) -> asn1_test_lib:compile("ValueTest", Config, [Rule|Opts]), testValueTest:main(). testOpenTypeImplicitTag(Config) -> test(Config, fun testOpenTypeImplicitTag/3). testOpenTypeImplicitTag(Config, Rule, Opts) -> asn1_test_lib:compile("OpenTypeImplicitTag", Config, [Rule|Opts]), testOpenTypeImplicitTag:main(Rule). rtUI(Config) -> test(Config, fun rtUI/3). rtUI(Config, Rule, Opts) -> asn1_test_lib:compile("Prim", Config, [Rule|Opts]), _ = 'Prim':info(), Rule = 'Prim':encoding_rule(), io:format("Default BIT STRING format: ~p\n", ['Prim':bit_string_format()]). testROSE(Config) -> test(Config, fun testROSE/3). testROSE(Config, Rule, Opts) -> asn1_test_lib:compile("Remote-Operations-Merged.set.asn1", Config, [Rule|Opts]). testINSTANCE_OF(Config) -> test(Config, fun testINSTANCE_OF/3). testINSTANCE_OF(Config, Rule, Opts) -> asn1_test_lib:compile("INSTANCEOF.asn1", Config, [Rule|Opts]), testINSTANCE_OF:main(Rule). testTCAP(Config) -> test(Config, fun testTCAP/3). testTCAP(Config, Rule, Opts) -> testTCAP:compile(Config, [Rule|Opts]), testTCAP:test(Rule, Config), case Rule of ber -> testTCAP:compile_asn1config(Config, [Rule, asn1config]), testTCAP:test_asn1config(); _ -> ok end. testDER(Config) -> test(Config, fun testDER/3, [ber]). testDER(Config, Rule, Opts) -> asn1_test_lib:compile("DERSpec", Config, [Rule, der|Opts]), testDER:test(). specialized_decodes(Config) -> test(Config, fun specialized_decodes/3, [ber]). specialized_decodes(Config, Rule, Opts) -> asn1_test_lib:compile_all(["PartialDecSeq.asn", "PartialDecSeq2.asn", "PartialDecSeq3.asn", "PartialDecMyHTTP.asn", "MEDIA-GATEWAY-CONTROL.asn", "P-Record", "PartialDecChoExtension.asn"], Config, [Rule,legacy_erlang_types,asn1config|Opts]), test_partial_incomplete_decode:test(Config), test_selective_decode:test(). special_decode_performance(Config) -> test(Config, fun special_decode_performance/3, [ber]). special_decode_performance(Config, Rule, Opts) -> Files = ["MEDIA-GATEWAY-CONTROL", "PartialDecSeq"], asn1_test_lib:compile_all(Files, Config, [Rule, asn1config|Opts]), test_special_decode_performance:go(all). test_ParamTypeInfObj(Config) -> asn1_test_lib:compile("IN-CS-1-Datatypes", Config, [ber]). test_WS_ParamClass(Config) -> test(Config, fun test_WS_ParamClass/3). test_WS_ParamClass(Config, Rule, Opts) -> asn1_test_lib:compile("InformationFramework", Config, [Rule|Opts]), ?only_ber(testWSParamClass:main(Rule)), ok. test_Defed_ObjectIdentifier(Config) -> test(Config, fun test_Defed_ObjectIdentifier/3). test_Defed_ObjectIdentifier(Config, Rule, Opts) -> asn1_test_lib:compile("UsefulDefinitions", Config, [Rule|Opts]). testSelectionType(Config) -> test(Config, fun testSelectionType/3). testSelectionType(Config, Rule, Opts) -> asn1_test_lib:compile("SelectionType", Config, [Rule|Opts]), testSelectionTypes:test(). testSSLspecs(Config) -> test(Config, fun testSSLspecs/3, [ber]). testSSLspecs(Config, Rule, Opts) -> ok = testSSLspecs:compile(Config, [Rule, compact_bit_string, der|Opts]), testSSLspecs:run(Rule), ok = testSSLspecs:compile_combined(Config, Rule), ok = testSSLspecs:run_combined(Rule). testNortel(Config) -> test(Config, fun testNortel/3). testNortel(Config, Rule, Opts) -> asn1_test_lib:compile("Nortel", Config, [Rule|Opts]). test_undecoded_rest(Config) -> test(Config, fun test_undecoded_rest/3). test_undecoded_rest(_Config,jer,_Opts) -> not relevant for JER test_undecoded_rest(Config, Rule, Opts) -> do_test_undecoded_rest(Config, Rule, Opts), do_test_undecoded_rest(Config, Rule, [no_ok_wrapper|Opts]), do_test_undecoded_rest(Config, Rule, [undec_rest|Opts]), do_test_undecoded_rest(Config, Rule, [no_ok_wrapper,undec_rest|Opts]). do_test_undecoded_rest(Config, Rule, Opts) -> asn1_test_lib:compile("P-Record", Config, [Rule|Opts]), test_undecoded_rest:test(Opts, Config). testTcapsystem(Config) -> test(Config, fun testTcapsystem/3). testTcapsystem(Config, Rule, Opts) -> testTcapsystem:compile(Config, [Rule|Opts]). testNBAPsystem(Config) -> test(Config, fun testNBAPsystem/3, [per]). testNBAPsystem(Config, Rule, Opts) -> testNBAPsystem:compile(Config, [Rule|Opts]), testNBAPsystem:test(Rule, Config). testS1AP(Config) -> test(Config, fun testS1AP/3). testS1AP(Config, Rule, Opts) -> S1AP = ["S1AP-CommonDataTypes", "S1AP-Constants", "S1AP-Containers", "S1AP-IEs", "S1AP-PDU-Contents", "S1AP-PDU-Descriptions"], asn1_test_lib:compile_all(S1AP, Config, [Rule|Opts]), %% OTP-7876. case Rule of per -> Enc = <<0,2,64,49,0,0,5,0,0,0,4,128,106,56,197,0,8,0,3,64,2,134,0, 100,64,8,0,66,240,153,0,7,192,16,0,67,64,6,0,66,240,153,70, 1,0,107,64,5,0,0,0,0,0>>, {ok,{initiatingMessage,_}} = 'S1AP-PDU-Descriptions':decode('S1AP-PDU', Enc); uper -> ok; ber -> ok; jer -> ok end. testRfcs() -> [{timetrap,{minutes,90}}]. testRfcs(Config) -> test(Config, fun testRfcs/3, [{ber,[der,?NO_MAPS_MODULE]}, {ber,[der,maps]}]). testRfcs(Config, Rule, Opts) -> case erlang:system_info(system_architecture) of "sparc-sun-solaris2.10" -> {skip,"Too slow for an old Sparc"}; _ -> testRfcs:compile(Config, Rule, Opts), testRfcs:test() end. test_compile_options(Config) -> ok = test_compile_options:wrong_path(Config), ok = test_compile_options:path(Config), ok = test_compile_options:noobj(Config), ok = test_compile_options:record_name_prefix(Config), ok = test_compile_options:verbose(Config), ok = test_compile_options:maps(Config), ok = test_compile_options:determinism(Config). testDoubleEllipses(Config) -> test(Config, fun testDoubleEllipses/3). testDoubleEllipses(Config, Rule, Opts) -> asn1_test_lib:compile("DoubleEllipses", Config, [Rule|Opts]), testDoubleEllipses:main(Rule). test_modified_x420(Config) -> test(Config, fun test_modified_x420/3, [ber]). test_modified_x420(Config, Rule, Opts) -> Files = [filename:join(modified_x420, F) || F <- ["PKCS7", "InformationFramework", "AuthenticationFramework"]], asn1_test_lib:compile_all(Files, Config, [Rule,der|Opts]), test_modified_x420:test(Config). test_x691(Config) -> test(Config, fun test_x691/3, [per, uper]). test_x691(Config, Rule, Opts) -> Files = ["P-RecordA1", "P-RecordA2", "P-RecordA3"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), test_x691:cases(Rule), %% OTP-7708. asn1_test_lib:compile("EUTRA-extract-55", Config, [legacy_erlang_types,Rule|Opts]), %% OTP-7763. Val = {'Seq',15,lists:duplicate(8, 0),[0],lists:duplicate(28, 0),15,true}, CompactVal = {'Seq',15,{0,<<0>>},{7,<<0>>},{4,<<0,0,0,0>>},15,true}, {ok,Bin} = 'EUTRA-extract-55':encode('Seq', Val), {ok,Bin} = 'EUTRA-extract-55':encode('Seq', CompactVal), OTP-7678 . asn1_test_lib:compile("UPERDefault", Config, [Rule|Opts]), DefVal = 'UPERDefault':seq(), {ok,DefBin} = 'UPERDefault':encode('Seq', DefVal), {ok,DefVal} = 'UPERDefault':decode('Seq', DefBin), case Rule of uper -> <<0,6,0>> = DefBin; _ -> ok end, ok. ticket_6143(Config) -> asn1_test_lib:compile("AA1", Config, [?NO_MAPS_MODULE]). testExtensionAdditionGroup(Config) -> test(Config, fun testExtensionAdditionGroup/3). testExtensionAdditionGroup(Config, Rule, Opts) -> asn1_test_lib:compile("Extension-Addition-Group", Config, [Rule|Opts]), asn1_test_lib:compile_erlang("extensionAdditionGroup", Config, [debug_info]), asn1_test_lib:compile("EUTRA-RRC-Definitions", Config, [Rule,{record_name_prefix,"RRC-"}|Opts]), extensionAdditionGroup:run(Rule). per_modules() -> [X || X <- test_modules()]. ber_modules() -> [X || X <- test_modules(), X =/= "H323-MESSAGES", X =/= "H235-SECURITY-MESSAGES"]. test_modules() -> ["BitStr", "CAP", "CommonDataTypes", "Constraints", "ContextSwitchingTypes", "CoverParser", "DS-EquipmentUser-CommonFunctionOrig-TransmissionPath", "Enum", "From", "H235-SECURITY-MESSAGES", "H323-MESSAGES", "HighTagNumbers", "Import", "Int", "MAP-commonDataTypes", "Null", "NullTest", "Octetstr", "One", "P-Record", "P", "Person", "PrimStrings", "Real", "XSeq", "XSeqOf", "XSet", "XSetOf", "String", "SwCDR", "Time", must be compiled before Seq and Set "Seq", "Set", "SetOf", "SeqOf", "Prim", "Cho", "Def", "Opt", "ELDAPv3", "LDAP", "SeqOptional2", "CCSNARG3"]. test_OTP_9688(Config) -> PrivDir = proplists:get_value(case_dir, Config), Data = " OTP-9688 DEFINITIONS ::= BEGIN foo INTEGER ::= 1 bar INTEGER ::= 42 Baz ::= INTEGER {x-y-z1(foo), x-y-z2(bar)} Qux ::= SEQUENCE {flerpInfo SEQUENCE {x INTEGER (-10 | -9 | (0..4))} OPTIONAL} END ", File = filename:join(PrivDir, "OTP-9688.asn1"), ok = file:write_file(File, Data), %% Does it compile with changes to asn1ct_check and asn1ct_gen_per_rt2ct? %% (see ticket) ok = asn1ct:compile(File, [{outdir, PrivDir}]). timer_compile(Config, Opts0) -> Files = ["H235-SECURITY-MESSAGES", "H323-MESSAGES"], Opts = [no_ok_wrapper,?NO_MAPS_MODULE|Opts0], asn1_test_lib:compile_all(Files, Config, Opts). testTimer_ber(Config) -> timer_compile(Config, [ber]), testTimer:go(). testTimer_per(Config) -> timer_compile(Config, [per]), testTimer:go(). testTimer_uper(Config) -> timer_compile(Config, [uper]), testTimer:go(). testTimer_ber_maps(Config) -> timer_compile(Config, [ber,maps]), testTimer:go(). testTimer_per_maps(Config) -> timer_compile(Config, [per,maps]), testTimer:go(). testTimer_uper_maps(Config) -> timer_compile(Config, [uper,maps]), testTimer:go(). Test of multiple - line comment , OTP-8043 testComment(Config) -> asn1_test_lib:compile("Comment", Config, []), asn1_test_lib:roundtrip('Comment', 'Seq', {'Seq',12,true}). testName2Number(Config) -> N2NOptions0 = [{n2n,Type} || Type <- ['Cause-Misc', 'CauseProtocol']], N2NOptions = [?NO_MAPS_MODULE|N2NOptions0], asn1_test_lib:compile("EnumN2N", Config, N2NOptions), 0 = 'EnumN2N':'name2num_Cause-Misc'('control-processing-overload'), 'unknown-PLMN' = 'EnumN2N':'num2name_Cause-Misc'(5), 4 = 'EnumN2N':name2num_CauseProtocol('semantic-error'), 'transfer-syntax-error' = 'EnumN2N':num2name_CauseProtocol(0), %% OTP-10144 %% Test that n2n option generates name2num and num2name functions supporting %% values not within the extension root if the enumeration type has an %% extension marker. N2NOptionsExt = [?NO_MAPS_MODULE,{n2n,'NoExt'},{n2n,'Ext'},{n2n,'Ext2'}], asn1_test_lib:compile("EnumN2N", Config, N2NOptionsExt), %% Previously, name2num and num2name was not generated if the type didn't %% have an extension marker: 0 = 'EnumN2N':name2num_NoExt('blue'), 2 = 'EnumN2N':name2num_NoExt('green'), blue = 'EnumN2N':num2name_NoExt(0), green = 'EnumN2N':num2name_NoExt(2), %% Test enumeration extension: 7 = 'EnumN2N':name2num_Ext2('orange'), orange = 'EnumN2N':num2name_Ext2(7), 7 is not defined in Ext , only in Ext2 . {asn1_enum, 7} = 'EnumN2N':num2name_Ext(7), 7 = 'EnumN2N':name2num_Ext({asn1_enum, 7}), 42 = 'EnumN2N':name2num_Ext2({asn1_enum, 42}), ok. ticket_7407(Config) -> Opts = [uper,?NO_MAPS_MODULE], asn1_test_lib:compile("EUTRA-extract-7407", Config, Opts), ticket_7407_code(true), asn1_test_lib:compile("EUTRA-extract-7407", Config, [no_final_padding|Opts]), ticket_7407_code(false). ticket_7407_code(FinalPadding) -> Msg1 = {Type1,_} = eutra1(msg), {ok,B1} = 'EUTRA-extract-7407':encode(Type1, Msg1), B1 = eutra1(result, FinalPadding), Msg2 = {Type2,_} = eutra2(msg), {ok,B2} = 'EUTRA-extract-7407':encode(Type2, Msg2), B2 = eutra2(result, FinalPadding), ok. eutra1(msg) -> {'BCCH-BCH-Message', {'MasterInformationBlock',<<2#0101:4>>,<<2#1010:4>>, {'PHICH-Configuration',short,ffs},<<2#10100000>>}}. eutra1(result, true) -> <<90,80,0>>; eutra1(result, false) -> <<90,80,0:1>>. eutra2(msg) -> {'BCCH-DL-SCH-Message', {c1, {systemInformation1, {'SystemInformationBlockType1', {'SystemInformationBlockType1_cellAccessRelatedInformation', [{'SystemInformationBlockType1_cellAccessRelatedInformation_plmn-IdentityList_SEQOF', {'PLMN-Identity'},true}, {'SystemInformationBlockType1_cellAccessRelatedInformation_plmn-IdentityList_SEQOF', {'PLMN-Identity'},false}, {'SystemInformationBlockType1_cellAccessRelatedInformation_plmn-IdentityList_SEQOF', {'PLMN-Identity'},true}], {'TrackingAreaCode'}, {'CellIdentity'}, false, true, true, true }, {'SystemInformationBlockType1_cellSelectionInfo',-50}, 24, [{'SystemInformationBlockType1_schedulinInformation_SEQOF', {'SystemInformationBlockType1_schedulinInformation_SEQOF_si-MessageType'}, ms320, {'SystemInformationBlockType1_schedulinInformation_SEQOF_sib-MappingInfo'}}], 0 } } } }. eutra2(result, true) -> 55 5C A5 E0 <<85,92,165,224>>; eutra2(result, false) -> <<85,92,165,14:4>>. -record('InitiatingMessage',{procedureCode,criticality,value}). -record('Iu-ReleaseCommand',{first,second}). ticket7904(Config) -> asn1_test_lib:compile("RANAPextract1", Config, [per]), Val1 = #'InitiatingMessage'{procedureCode=1, criticality=ignore, value=#'Iu-ReleaseCommand'{ first=13, second=true}}, {ok,_} = 'RANAPextract1':encode('InitiatingMessage', Val1), {ok,_} = 'RANAPextract1':encode('InitiatingMessage', Val1). %% Make sure that functions exported from other modules are %% actually used. xref(_Config) -> S = ?FUNCTION_NAME, xref:start(S), xref:set_default(S, [{verbose,false},{warnings,false},{builtins,true}]), Test = filename:dirname(code:which(?MODULE)), {ok,_PMs} = xref:add_directory(S, Test), Q = "X - XU - \".*_SUITE\" : Mod", UnusedExports = xref:q(S, Q), xref:stop(S), case UnusedExports of {ok,[]} -> ok; {ok,[_|_]=Res} -> ct:fail("Exported, but unused: ~p\n", [Res]) end. %% Ensure that all functions that are implicitly exported by %% 'export_all' in this module are actually used. xref_export_all(_Config) -> S = ?FUNCTION_NAME, xref:start(S), xref:set_default(S, [{verbose,false},{warnings,false},{builtins,true}]), {ok,_PMs} = xref:add_module(S, code:which(?MODULE)), AllCalled = all_called(), Def = "Called := " ++ lists:flatten(io_lib:format("~p", [AllCalled])), {ok,_} = xref:q(S, Def), {ok,Unused} = xref:q(S, "X - Called - range (closure E | Called)"), xref:stop(S), case Unused -- [{?MODULE,otp_14440_decode,0}] of [] -> ok; [_|_] -> Msg = [io_lib:format("~p:~p/~p\n", [M,F,A]) || {M,F,A} <- Unused], ct:fail("There are unused functions:\n\n~s\n", [Msg]) end. %% Collect all functions that common_test will call in this module. all_called() -> [{?MODULE,end_per_group,2}, {?MODULE,end_per_suite,1}, {?MODULE,end_per_testcase,2}, {?MODULE,init_per_group,2}, {?MODULE,init_per_suite,1}, {?MODULE,init_per_testcase,2}, {?MODULE,suite,0}] ++ all_called_1(all() ++ groups()). all_called_1([{_,_}|T]) -> all_called_1(T); all_called_1([{_Name,_Flags,Fs}|T]) -> all_called_1(Fs ++ T); all_called_1([F|T]) when is_atom(F) -> L = case erlang:function_exported(?MODULE, F, 0) of false -> [{?MODULE,F,1}]; true -> [{?MODULE,F,0},{?MODULE,F,1}] end, L ++ all_called_1(T); all_called_1([]) -> [].
null
https://raw.githubusercontent.com/erlang/otp/63abc6807d9998e8c44bc86cc673912b539ac397/lib/asn1/test/asn1_SUITE.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% Suppress compilation of an addititional module compiled for maps. ------------------------------------------------------------------------------ Suite definition ------------------------------------------------------------------------------ Some heavy tests. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Test runners ------------------------------------------------------------------------------ All skipped Run the actual test function ------------------------------------------------------------------------------ Test cases ------------------------------------------------------------------------------ (if any). Test of OTP-2523 ENUMERATED with extensionmark. Test of OTP-2738 Detect corrupt optional component. Because of the recursive definition of 'Filter' in the LDAP module, the construction of a sample value for 'Filter' is not guaranteed to terminate. records used by test-case default We get this if stack depth limit kicks in: subtype constraint is not checked OTP-7876. OTP-7708. OTP-7763. Does it compile with changes to asn1ct_check and asn1ct_gen_per_rt2ct? (see ticket) OTP-10144 Test that n2n option generates name2num and num2name functions supporting values not within the extension root if the enumeration type has an extension marker. Previously, name2num and num2name was not generated if the type didn't have an extension marker: Test enumeration extension: Make sure that functions exported from other modules are actually used. Ensure that all functions that are implicitly exported by 'export_all' in this module are actually used. Collect all functions that common_test will call in this module.
Copyright Ericsson AB 2001 - 2022 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , Purpose : Test suite for the ASN.1 application -module(asn1_SUITE). -define(NO_MAPS_MODULE, asn1_test_lib_no_maps). -define(only_ber(Func), if Rule =:= ber -> Func; true -> ok end). -compile(export_all). -include_lib("common_test/include/ct.hrl"). suite() -> [{ct_hooks, [ts_install_cth]}, {timetrap,{minutes,60}}]. all() -> [xref, xref_export_all, c_string, constraint_equivalence, ber_decode_invalid_length, ber_choiceinseq, ber_optional, tagdefault_automatic, cover, parse, test_undecoded_rest, specialized_decodes, special_decode_performance, testMegaco, testConstraints, testCompactBitString, default, testPrim, rtUI, testPrimStrings, per, ber, der, h323test, testExtensibilityImplied, testChoice, testDefaultOctetString, testMultipleLevels, testOpt, testSeqDefault, testMaps, testTypeValueNotation, testExternal, testSeqExtension, testSeqOptional, testSeqPrim, testSeqTypeRefCho, testSeqTypeRefPrim, testSeqTypeRefSeq, testSeqTypeRefSet, testSeqOf, testSeqOfIndefinite, testSeqOfCho, testSeqOfChoExt, testExtensionAdditionGroup, testSet, testSetOf, testEnumExt, value_test, testSeq2738, constructed, ber_decode_error, otp_14440, testSeqSetIndefinite, testChoiceIndefinite, per_open_type, testInfObjectClass, testUniqueObjectSets, testInfObjExtract, testParam, testFragmented, testMergeCompile, testobj, testDeepTConstr, testImport, testDER, testDEFAULT, testExtensionDefault, testMvrasn6, testContextSwitchingTypes, testOpenTypeImplicitTag, testROSE, testINSTANCE_OF, testTCAP, test_ParamTypeInfObj, test_Defed_ObjectIdentifier, testSelectionType, testSSLspecs, testNortel, test_WS_ParamClass, test_modified_x420, testTcapsystem, testNBAPsystem, testS1AP, testRfcs, test_compile_options, testDoubleEllipses, test_x691, ticket_6143, test_OTP_9688, testValueTest, testComment, testName2Number, ticket_7407, ticket7904, {group, performance}]. groups() -> [{performance, [], [testTimer_ber, testTimer_ber_maps, testTimer_per, testTimer_per_maps, testTimer_uper, testTimer_uper_maps]}]. Init / end init_per_suite(Config) -> Config. end_per_suite(_Config) -> ok. init_per_group(_GroupName, Config) -> Config. end_per_group(_GroupName, Config) -> Config. init_per_testcase(Func, Config) -> CaseDir = filename:join(proplists:get_value(priv_dir, Config), Func), ok = filelib:ensure_dir(filename:join([CaseDir, dummy_file])), true = code:add_patha(CaseDir), [{case_dir, CaseDir}|Config]. end_per_testcase(_Func, Config) -> CaseDir = proplists:get_value(case_dir, Config), asn1_test_lib:rm_dirs([CaseDir]), code:del_path(CaseDir). have_jsonlib() -> case code:which(jsx) of non_existing -> false; _ -> true end. test(Config, TestF) -> TestJer = case have_jsonlib() of true -> [jer]; false -> [] end, test(Config, TestF, [per, uper, ber] ++ TestJer), case TestJer of [] -> {comment,"skipped JER"}; _ -> ok end. test(Config, TestF, Rules) -> Fun = fun(C, R, O) -> M = element(2, erlang:fun_info(TestF, module)), F = element(2, erlang:fun_info(TestF, name)), io:format("Running ~p:~p with ~p...~n", [M, F, {R, O}]), try TestF(C, R, O) catch Class:Reason:Stk -> NewReason = {Reason, [{rule, R}, {options, O}]}, erlang:raise(Class, NewReason, Stk) end end, Result = [run_case(Config, Fun, rule(Rule), opts(Rule)) || Rule <- Rules], case lists:usort(Result) of At least one test ran end. rule(A) when is_atom(A) -> A; rule({A, _Opts} ) -> A. opts(Rule) when is_atom(Rule) -> []; opts({_Rule, Opts}) -> Opts. run_case(Config, Fun, Rule, Opts) -> CaseDir = proplists:get_value(case_dir, Config), Dir = filename:join([CaseDir, join(Rule, Opts)]), ok = filelib:ensure_dir(filename:join([Dir, dummy_file])), replace_path(CaseDir, Dir), NewConfig = lists:keyreplace(case_dir, 1, Config, {case_dir, Dir}), Result = Fun(NewConfig, Rule, Opts), replace_path(Dir, CaseDir), case Result of {skip, _Reason} -> Result; _ -> true end. replace_path(PathA, PathB) -> true = code:del_path(PathA), true = code:add_patha(PathB). join(Rule, Opts) -> lists:join("_", [atom_to_list(Rule)|lists:map(fun atom_to_list/1, Opts)]). Cover run - time functions that are only called by the ASN.1 compiler cover(_) -> Wc = filename:join([code:lib_dir(asn1),"ebin","asn1ct_eval_*.beam"]), Beams = filelib:wildcard(Wc), true = Beams =/= [], [begin M0 = filename:basename(Beam), M1 = filename:rootname(M0), M = list_to_atom(M1), "asn1ct_eval_" ++ Group0 = M1, Group = list_to_atom(Group0), io:format("%%\n" "%% ~s\n" "%%\n", [M]), asn1ct_func:start_link(), [asn1ct_func:need({Group,F,A}) || {F,A} <- M:module_info(exports), F =/= module_info], asn1ct_func:generate(group_leader()) end || Beam <- Beams], ok. testPrim(Config) -> test(Config, fun testPrim/3). testPrim(Config, Rule, Opts) -> Files = ["Prim","Real"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), do_test_prim(Rule, false), asn1_test_lib:compile_all(Files, Config, [no_ok_wrapper,Rule|Opts]), do_test_prim(Rule, true). do_test_prim(Rule, NoOkWrapper) -> io:format("No ok wrapper: ~p\n", [NoOkWrapper]), put(no_ok_wrapper, NoOkWrapper), testPrim:bool(Rule), testPrim:int(Rule), testPrim:enum(Rule), testPrim:obj_id(Rule), testPrim:rel_oid(Rule), testPrim:null(Rule), Temporary workaround for JER testCompactBitString(Config) -> test(Config, fun testCompactBitString/3). testCompactBitString(Config, Rule, Opts) -> Files = ["PrimStrings", "Constraints"], asn1_test_lib:compile_all(Files, Config, [Rule, compact_bit_string|Opts]), testCompactBitString:compact_bit_string(Rule), testCompactBitString:bit_string_unnamed(Rule), testCompactBitString:bit_string_unnamed(Rule), testCompactBitString:ticket_7734(Rule), testCompactBitString:otp_4869(Rule). testPrimStrings(Config) -> test(Config, fun testPrimStrings/3, [ber,{ber,[der]},per,uper]). testPrimStrings(Config, Rule, Opts) -> LegacyOpts = [legacy_erlang_types|Opts], Files = ["PrimStrings", "BitStr"], asn1_test_lib:compile_all(Files, Config, [Rule|LegacyOpts]), testPrimStrings_cases(Rule, LegacyOpts), asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testPrimStrings_cases(Rule, Opts), asn1_test_lib:compile_all(Files, Config, [legacy_bit_string,Rule|Opts]), testPrimStrings:bit_string(Rule, Opts), asn1_test_lib:compile_all(Files, Config, [compact_bit_string,Rule|Opts]), testPrimStrings:bit_string(Rule, Opts), testPrimStrings:more_strings(Rule). testPrimStrings_cases(Rule, Opts) -> testPrimStrings:bit_string(Rule, Opts), testPrimStrings:octet_string(Rule), testPrimStrings:numeric_string(Rule), testPrimStrings:other_strings(Rule), testPrimStrings:universal_string(Rule), testPrimStrings:bmp_string(Rule), testPrimStrings:times(Rule), testPrimStrings:utf8_string(Rule), testPrimStrings:fragmented(Rule). testExternal(Config) -> test(Config, fun testExternal/3). testExternal(Config, Rule, Opts) -> asn1_test_lib:compile_all(["External", "ChoExternal", "PrimExternal", "SeqExternal", "SeqOfExternal", "SeqOfTag", "SeqTag", "SetExtension", "SetExternal", "SetOfExternal", "SetOfTag", "SetTag"], Config, [Rule|Opts]), testChoExternal:external(Rule), testPrimExternal:external(Rule), testSeqExternal:main(Rule), testSeqOfExternal:main(Rule), testSeqOfTag:main(Rule), testSeqTag:main(Rule), testSetExtension:main(Rule), testSetExternal:main(Rule), testSetOfExternal:main(Rule), testSetOfTag:main(Rule), testSetTag:main(Rule). testExtensibilityImplied(Config) -> test(Config, fun testExtensibilityImplied/3). testExtensibilityImplied(Config, Rule, Opts) -> asn1_test_lib:compile("ExtensibilityImplied", Config, [Rule,no_ok_wrapper|Opts]), testExtensibilityImplied:main(Rule). testChoice(Config) -> test(Config, fun testChoice/3). testChoice(Config, Rule, Opts) -> Files = ["ChoPrim", "ChoExtension", "ChoOptional", "ChoOptionalImplicitTag", "ChoRecursive", "ChoTypeRefCho", "ChoTypeRefPrim", "ChoTypeRefSeq", "ChoTypeRefSet"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testChoPrim:bool(Rule), testChoPrim:int(Rule), testChoExtension:extension(Rule), testChoOptional:run(), testChoRecursive:recursive(Rule), testChoTypeRefCho:choice(Rule), testChoTypeRefPrim:prim(Rule), testChoTypeRefSeq:seq(Rule), testChoTypeRefSet:set(Rule). testDefaultOctetString(Config) -> test(Config, fun testDefaultOctetString/3). testDefaultOctetString(Config, Rule, Opts) -> asn1_test_lib:compile("DefaultOctetString", Config, [Rule|Opts]), testDefaultOctetString:dos(Rule). testMultipleLevels(Config) -> test(Config, fun testMultipleLevels/3). testMultipleLevels(Config, Rule, Opts) -> asn1_test_lib:compile("MultipleLevels", Config, [Rule|Opts]), testMultipleLevels:main(Rule). testDEFAULT(Config) -> test(Config, fun testDEFAULT/3, [ber,{ber,[der]},per,uper]). testDEFAULT(Config, Rule, Opts) -> asn1_test_lib:compile_all(["Def","Default"], Config, [Rule|Opts]), testDef:main(Rule), testSeqSetDefaultVal:main(Rule, Opts), asn1_test_lib:compile_all(["Def","Default"], Config, [legacy_erlang_types,Rule|Opts]), testDef:main(Rule), testSeqSetDefaultVal:main(Rule, Opts). testExtensionDefault(Config) -> test(Config, fun testExtensionDefault/3). testExtensionDefault(Config, Rule, Opts) -> asn1_test_lib:compile_all(["ExtensionDefault"], Config, [Rule|Opts]), testExtensionDefault:main(Rule). testMaps(Config) -> Jer = case have_jsonlib() of true -> [{jer,[maps,no_ok_wrapper]}]; false -> [] end, RulesAndOptions = [{ber,[maps,no_ok_wrapper]}, {ber,[maps,der,no_ok_wrapper]}, {per,[maps,no_ok_wrapper]}, {uper,[maps,no_ok_wrapper]}] ++ Jer, test(Config, fun testMaps/3, RulesAndOptions), case Jer of [] -> {comment,"skipped JER"}; _ -> ok end. testMaps(Config, Rule, Opts) -> asn1_test_lib:compile_all(['Maps'], Config, [Rule|Opts]), testMaps:main(Rule). testOpt(Config) -> test(Config, fun testOpt/3). testOpt(Config, Rule, Opts) -> asn1_test_lib:compile("Opt", Config, [Rule|Opts]), testOpt:main(Rule). testEnumExt(Config) -> test(Config, fun testEnumExt/3). testEnumExt(Config, Rule, Opts) -> asn1_test_lib:compile("EnumExt", Config, [Rule|Opts]), testEnumExt:main(Rule). testSeqDefault(Config) -> test(Config, fun testSeqDefault/3). testSeqDefault(Config, Rule, Opts) -> asn1_test_lib:compile("SeqDefault", Config, [Rule|Opts]), testSeqDefault:main(Rule). testSeqExtension(Config) -> test(Config, fun testSeqExtension/3, [ber,uper]). testSeqExtension(Config, Rule, Opts) -> asn1_test_lib:compile_all(["External", "SeqExtension", "SeqExtension2"], Config, [Rule|Opts]), DataDir = proplists:get_value(data_dir, Config), testSeqExtension:main(Rule, DataDir, [Rule|Opts]). testSeqOptional(Config) -> test(Config, fun testSeqOptional/3). testSeqOptional(Config, Rule, Opts) -> asn1_test_lib:compile("SeqOptional", Config, [Rule|Opts]), testSeqOptional:main(Rule). testSeqPrim(Config) -> test(Config, fun testSeqPrim/3). testSeqPrim(Config, Rule, Opts) -> asn1_test_lib:compile("SeqPrim", Config, [Rule|Opts]), testSeqPrim:main(Rule). testSeq2738(Config) -> test(Config, fun testSeq2738/3). testSeq2738(Config, Rule, Opts) -> asn1_test_lib:compile("Seq2738", Config, [Rule|Opts]), testSeq2738:main(Rule). testSeqTypeRefCho(Config) -> test(Config, fun testSeqTypeRefCho/3). testSeqTypeRefCho(Config, Rule, Opts) -> asn1_test_lib:compile("SeqTypeRefCho", Config, [Rule|Opts]), testSeqTypeRefCho:main(Rule). testSeqTypeRefPrim(Config) -> test(Config, fun testSeqTypeRefPrim/3). testSeqTypeRefPrim(Config, Rule, Opts) -> asn1_test_lib:compile("SeqTypeRefPrim", Config, [Rule|Opts]), testSeqTypeRefPrim:main(Rule). testSeqTypeRefSeq(Config) -> test(Config, fun testSeqTypeRefSeq/3). testSeqTypeRefSeq(Config, Rule, Opts) -> asn1_test_lib:compile("SeqTypeRefSeq", Config, [Rule|Opts]), testSeqTypeRefSeq:main(Rule). testSeqTypeRefSet(Config) -> test(Config, fun testSeqTypeRefSet/3). testSeqTypeRefSet(Config, Rule, Opts) -> asn1_test_lib:compile("SeqTypeRefSet", Config, [Rule|Opts]), testSeqTypeRefSet:main(Rule). testSeqOf(Config) -> test(Config, fun testSeqOf/3). testSeqOf(Config, Rule, Opts) -> asn1_test_lib:compile_all(["SeqOf", "SeqOfEnum", "XSeqOf"], Config, [Rule|Opts]), testSeqOf:main(Rule). testSeqOfCho(Config) -> test(Config, fun testSeqOfCho/3). testSeqOfCho(Config, Rule, Opts) -> asn1_test_lib:compile("SeqOfCho", Config, [Rule|Opts]), testSeqOfCho:main(Rule). testSeqOfChoExt(Config) -> test(Config, fun testSeqOfChoExt/3). testSeqOfChoExt(Config, Rule, Opts) -> asn1_test_lib:compile("SeqOfChoExt", Config, [Rule|Opts]), testSeqOfChoExt:main(Rule). testSeqOfIndefinite(Config) -> test(Config, fun testSeqOfIndefinite/3, [ber]). testSeqOfIndefinite(Config, Rule, Opts) -> Files = ["Mvrasn-Constants-1", "Mvrasn-DataTypes-1", "Mvrasn-21-4", "Mvrasn-20-4", "Mvrasn-19-4", "Mvrasn-18-4", "Mvrasn-17-4", "Mvrasn-15-4", "Mvrasn-14-4", "Mvrasn-11-4", "SeqOf"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testSeqOfIndefinite:main(). testSet(Config) -> test(Config, fun testSet/3). testSet(Config, Rule, Opts) -> Files = ["SetDefault", "SetOptional", "SetPrim", "SetTypeRefCho", "SetTypeRefPrim", "SetTypeRefSeq", "SetTypeRefSet"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testSetDefault:main(Rule), testSetOptional:ticket_7533(Rule), testSetOptional:main(Rule), testSetPrim:main(Rule), testSetTypeRefCho:main(Rule), testSetTypeRefPrim:main(Rule), testSetTypeRefSeq:main(Rule), testSetTypeRefSet:main(Rule). testSetOf(Config) -> test(Config, fun testSetOf/3). testSetOf(Config, Rule, Opts) -> Files = ["SetOf", "SetOfCho"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testSetOf:main(Rule), testSetOfCho:main(Rule). c_string(Config) -> test(Config, fun c_string/3). c_string(Config, Rule, Opts) -> asn1_test_lib:compile("String", Config, [Rule|Opts]), asn1ct:test('String'). constraint_equivalence(Config) -> constraint_equivalence_abs(Config), test(Config, fun constraint_equivalence/3). constraint_equivalence(Config, Rule, Opts) -> M = 'ConstraintEquivalence', asn1_test_lib:compile(M, Config, [Rule|Opts]). constraint_equivalence_abs(Config) -> DataDir = proplists:get_value(data_dir, Config), CaseDir = proplists:get_value(case_dir, Config), Asn1Spec = "ConstraintEquivalence", Asn1Src = filename:join(DataDir, Asn1Spec), ok = asn1ct:compile(Asn1Src, [abs,{outdir,CaseDir}]), AbsFile = filename:join(CaseDir, Asn1Spec++".abs"), {ok,Terms} = file:consult(AbsFile), Cs = [begin Constraints = element(4, Type), Name1 = atom_to_list(Name0), {Name,_} = lists:splitwith(fun(C) -> C =/= $X end, Name1), {Name,Constraints} end || {typedef,_,_,Name0,Type} <- Terms], R = sofs:relation(Cs, [{name,constraint}]), F0 = sofs:relation_to_family(R), F = sofs:to_external(F0), Diff = [E || {_,L}=E <- F, length(L) > 1], case Diff of [] -> ok; [_|_] -> io:put_chars("Not equivalent:\n"), [io:format("~s: ~p\n", [N,D]) || {N,D} <- Diff], ct:fail(length(Diff)) end. parse(Config) -> [asn1_test_lib:compile(M, Config, [abs]) || M <- test_modules()]. per(Config) -> test(Config, fun per/3, [per,uper,{per,[maps]},{uper,[maps]}]). per(Config, Rule, Opts) -> module_test(per_modules(), Config, Rule, Opts). ber(Config) -> test(Config, fun ber/3, [ber,{ber,[maps]}]). ber(Config, Rule, Opts) -> module_test(ber_modules(), Config, Rule, Opts). der(Config) -> asn1_test_lib:compile_all(ber_modules(), Config, [der]). module_test(Modules, Config, Rule, Opts) -> asn1_test_lib:compile_all(Modules, Config, [Rule,?NO_MAPS_MODULE|Opts]), _ = [do_module_test(M, Config, Opts) || M <- Modules], ok. do_module_test(M0, Config, Opts) -> case list_to_atom(M0) of 'LDAP' -> ok; M -> TestOpts = [{i, proplists:get_value(case_dir, Config)}], case asn1ct:test(M, TestOpts) of ok -> ok; Error -> erlang:error({test_failed, M, Opts, Error}) end end. ber_decode_invalid_length(_Config) -> Bin = <<48,129,157,48,0,2,1,2,164,0,48,129,154,49,24,48,22,6, 3,85,4,10,19,15,69,120,97,109,112,108,101,32,67,111, 109,112,97,110,121,49,29,48,27,6,9,42,134,72,134,247, 13,1,9,1,22,14,99,97,64,101,120,97,109,112,108,101,46, 99,111,109,49,13,48,11,6,3,85,4,7,19,4,79,117,108,117, 49,26,48,24,6,3,85,4,8,19,17,80,111,104,106,111,105, 115,45,80,111,104,106,97,110,109,97,97,49,11,48,9,6,3, 85,4,6,19,2,70,73,49,19,48,17,6,3,85,4,3,19,10,69,120, 97,109,112,108,101,32,67,65,49,11,48,16,6,3,85,4,11, 19,9,84,101>>, {'EXIT',{error,{asn1,{invalid_value,12}}}} = (catch asn1rt_nif:decode_ber_tlv(Bin)), ok. ber_choiceinseq(Config) -> test(Config, fun ber_choiceinseq/3, [ber]). ber_choiceinseq(Config, Rule, Opts) -> asn1_test_lib:compile("ChoiceInSeq", Config, [Rule|Opts]). ber_optional(Config) -> test(Config, fun ber_optional/3, [ber]). ber_optional(Config, Rule, Opts) -> asn1_test_lib:compile("SOpttest", Config, [Rule|Opts]), V = {'S', {'A', 10, asn1_NOVALUE, asn1_NOVALUE}, {'B', asn1_NOVALUE, asn1_NOVALUE, asn1_NOVALUE}, {'C', asn1_NOVALUE, 111, asn1_NOVALUE}}, asn1_test_lib:roundtrip('SOpttest', 'S', V). tagdefault_automatic(Config) -> test(Config, fun tagdefault_automatic/3, [ber]). tagdefault_automatic(Config, Rule, Opts) -> asn1_test_lib:compile("TAGDEFAULT-AUTOMATIC", Config, [Rule|Opts]), << 48,8,128,2,100,101,129,2,110,111 >> = asn1_test_lib:roundtrip_enc('TAGDEFAULT-AUTOMATIC', 'Tagged', {'Tagged', << 100,101 >>, << 110,111 >>}), << 48,8,128,2,100,101,129,2,110,111 >> = asn1_test_lib:roundtrip_enc('TAGDEFAULT-AUTOMATIC', 'Untagged', {'Untagged', << 100,101 >>, << 110,111 >>}), << 48,8,4,2,100,101,130,2,110,111 >> = asn1_test_lib:roundtrip_enc('TAGDEFAULT-AUTOMATIC', 'Mixed', {'Mixed', << 100,101 >>, << 110,111 >>}), ok. -record('Def1', {bool0, bool1 = asn1_DEFAULT, bool2 = asn1_DEFAULT, bool3 = asn1_DEFAULT}). default(Config) -> test(Config, fun default/3). default(Config, Rule, Opts) -> asn1_test_lib:compile("Def", Config, [Rule|Opts]), asn1_test_lib:roundtrip('Def', 'Def1', #'Def1'{bool0=true}, #'Def1'{bool0=true,bool1=false, bool2=false,bool3=false}), asn1_test_lib:roundtrip('Def', 'Def1', #'Def1'{bool0=true,bool2=false}, #'Def1'{bool0=true,bool1=false, bool2=false,bool3=false}). value_test(Config) -> test(Config, fun value_test/3). value_test(Config, Rule, Opts) -> asn1_test_lib:compile("ObjIdValues", Config, [Rule|Opts]), {ok, _} = asn1ct:test('ObjIdValues', 'ObjIdType', 'ObjIdValues':'mobileDomainId'()). constructed(Config) -> test(Config, fun constructed/3, [ber]). constructed(Config, Rule, Opts) -> asn1_test_lib:compile("Constructed", Config, [Rule|Opts]), <<40,3,1,1,0>> = asn1_test_lib:roundtrip_enc('Constructed', 'S', {'S',false}), <<40,5,48,3,1,1,0>> = asn1_test_lib:roundtrip_enc('Constructed', 'S2', {'S2',false}), <<136,1,10>> = asn1_test_lib:roundtrip_enc('Constructed', 'I', 10), ok. ber_decode_error(Config) -> test(Config, fun ber_decode_error/3, [ber]). ber_decode_error(Config, Rule, Opts) -> asn1_test_lib:compile("Constructed", Config, [Rule|Opts]), ber_decode_error:run(Opts). otp_14440(_Config) -> {ok, Peer, N} = ?CT_PEER(), Result = rpc:call(N, ?MODULE, otp_14440_decode, []), io:format("Decode result = ~p~n", [Result]), peer:stop(Peer), case Result of {exit,{error,{asn1,{invalid_value,5}}}} -> ok; {exit,{error,{asn1,{unknown,_}}}} -> ok; _ -> ct:fail(Result) end. otp_14440_decode() -> Data = iolist_to_binary( lists:duplicate( 32, list_to_binary(lists:duplicate(1024, 16#7f)))), try asn1rt_nif:decode_ber_tlv(Data) of Result -> {unexpected_return,Result} catch Class:Reason -> {Class,Reason} end. h323test(Config) -> test(Config, fun h323test/3). h323test(Config, Rule, Opts) -> Files = ["H235-SECURITY-MESSAGES", "H323-MESSAGES", "MULTIMEDIA-SYSTEM-CONTROL"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), h323test:run(Rule). per_open_type(Config) -> test(Config, fun per_open_type/3, [per]). per_open_type(Config, Rule, Opts) -> asn1_test_lib:compile("OpenType", Config, [Rule|Opts]), {ok, _} = asn1ct:test('OpenType', 'Ot', {'Stype', 10, true}). testConstraints(Config) -> test(Config, fun testConstraints/3). testConstraints(Config, Rule, Opts) -> Files = ["Constraints", "LargeConstraints"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testConstraints:int_constraints(Rule), case Rule of ber -> ok; _ -> testConstraints:refed_NNL_name(Rule) end. testSeqSetIndefinite(Config) -> test(Config, fun testSeqSetIndefinite/3, [ber]). testSeqSetIndefinite(Config, Rule, Opts) -> asn1_test_lib:compile("SeqSetIndefinite", Config, [Rule|Opts]), testSeqSetIndefinite:main(). testChoiceIndefinite(Config) -> test(Config, fun testChoiceIndefinite/3, [ber]). testChoiceIndefinite(Config, Rule, Opts) -> asn1_test_lib:compile("ChoiceIndef", Config, [Rule|Opts]), testChoiceIndefinite:main(Rule). testInfObjectClass(Config) -> test(Config, fun testInfObjectClass/3). testInfObjectClass(Config, Rule, Opts) -> Files = ["ErrorClass", "InfClass"], InfObjFiles = ["RANAPextract1", "InfObj", "MAP-ExtensionDataTypes", "Objects", "INAPv2extract"], RANAPFiles = ["RANAP-CommonDataTypes", "RANAP-Constants", "RANAP-Containers", "RANAP-IEs", "RANAP-PDU-Contents", "RANAP-PDU-Descriptions"], asn1_test_lib:compile_all(Files ++ InfObjFiles ++ RANAPFiles, Config, [Rule|Opts]), testInfObjectClass:main(Rule), testInfObj:main(Rule). testUniqueObjectSets(Config) -> test(Config, fun testUniqueObjectSets/3). testUniqueObjectSets(Config, Rule, Opts) -> CaseDir = proplists:get_value(case_dir, Config), testUniqueObjectSets:main(CaseDir, Rule, Opts). testInfObjExtract(Config) -> test(Config, fun testInfObjExtract/3). testInfObjExtract(Config, Rule, Opts) -> asn1_test_lib:compile("InfObjExtract", Config, [Rule|Opts]), testInfObjExtract:main(Rule). testParam(Config) -> test(Config, fun testParam/3, [ber,{ber,[der]},per,uper]). testParam(Config, Rule, Opts) -> Files = ["ParamBasic","Param","Param2"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testParamBasic:main(Rule), testParameterizedInfObj:main(Config, Rule), asn1_test_lib:compile("Param", Config, [legacy_erlang_types,Rule|Opts]), testParameterizedInfObj:param(Rule). testFragmented(Config) -> test(Config, fun testFragmented/3). testFragmented(Config, Rule, Opts) -> asn1_test_lib:compile("Fragmented", Config, [Rule|Opts]), testFragmented:main(Rule). testMergeCompile(Config) -> test(Config, fun testMergeCompile/3). testMergeCompile(Config, Rule, Opts) -> Files = ["MS.set.asn", "RANAPSET.set.asn1", "Mvrasn4.set.asn", "Mvrasn6.set.asn"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), testMergeCompile:main(Rule), testMergeCompile:mvrasn(Rule). testobj(Config) -> test(Config, fun testobj/3). testobj(_Config, jer, _Opts) -> ok; testobj(Config, Rule, Opts) -> asn1_test_lib:compile("RANAP", Config, [legacy_erlang_types, Rule|Opts]), asn1_test_lib:compile_erlang("testobj", Config, []), ok = testobj:run(), ok = testParameterizedInfObj:ranap(Rule). testDeepTConstr(Config) -> test(Config, fun testDeepTConstr/3). testDeepTConstr(Config, Rule, Opts) -> asn1_test_lib:compile_all(["TConstrChoice", "TConstr"], Config, [Rule|Opts]), testDeepTConstr:main(Rule). testImport(Config) -> test(Config, fun testImport/3). testImport(Config, Rule, Opts) -> Files = ["ImportsFrom","ImportsFrom2","ImportsFrom3", "Importing","Exporting"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), 42 = 'ImportsFrom':i(), testImporting:main(Rule), ok. testMegaco(Config) -> test(Config, fun testMegaco/3). testMegaco(Config, Rule, Opts) -> {ok, Module1, Module2} = testMegaco:compile(Config, Rule, [legacy_erlang_types|Opts]), ok = testMegaco:main(Module1, Config), ok = testMegaco:main(Module2, Config). testMvrasn6(Config) -> test(Config, fun testMvrasn6/3). testMvrasn6(Config, Rule, Opts) -> asn1_test_lib:compile_all(["Mvrasn-21-4", "Mvrasn-20-6", "Mvrasn-19-6", "Mvrasn-15-6", "Mvrasn-18-6", "Mvrasn-14-6", "Mvrasn-11-6"], Config, [Rule|Opts]). testContextSwitchingTypes(Config) -> test(Config, fun testContextSwitchingTypes/3). testContextSwitchingTypes(Config, Rule, Opts) -> asn1_test_lib:compile("ContextSwitchingTypes", Config, [Rule|Opts]), testContextSwitchingTypes:test(Rule,Config). testTypeValueNotation(Config) -> test(Config, fun testTypeValueNotation/3). testTypeValueNotation(Config, Rule, Opts) -> asn1_test_lib:compile("SeqTypeRefPrim", Config, [Rule|Opts]), testTypeValueNotation:main(Rule, Opts). testValueTest(Config) -> test(Config, fun testValueTest/3). testValueTest(Config, Rule, Opts) -> asn1_test_lib:compile("ValueTest", Config, [Rule|Opts]), testValueTest:main(). testOpenTypeImplicitTag(Config) -> test(Config, fun testOpenTypeImplicitTag/3). testOpenTypeImplicitTag(Config, Rule, Opts) -> asn1_test_lib:compile("OpenTypeImplicitTag", Config, [Rule|Opts]), testOpenTypeImplicitTag:main(Rule). rtUI(Config) -> test(Config, fun rtUI/3). rtUI(Config, Rule, Opts) -> asn1_test_lib:compile("Prim", Config, [Rule|Opts]), _ = 'Prim':info(), Rule = 'Prim':encoding_rule(), io:format("Default BIT STRING format: ~p\n", ['Prim':bit_string_format()]). testROSE(Config) -> test(Config, fun testROSE/3). testROSE(Config, Rule, Opts) -> asn1_test_lib:compile("Remote-Operations-Merged.set.asn1", Config, [Rule|Opts]). testINSTANCE_OF(Config) -> test(Config, fun testINSTANCE_OF/3). testINSTANCE_OF(Config, Rule, Opts) -> asn1_test_lib:compile("INSTANCEOF.asn1", Config, [Rule|Opts]), testINSTANCE_OF:main(Rule). testTCAP(Config) -> test(Config, fun testTCAP/3). testTCAP(Config, Rule, Opts) -> testTCAP:compile(Config, [Rule|Opts]), testTCAP:test(Rule, Config), case Rule of ber -> testTCAP:compile_asn1config(Config, [Rule, asn1config]), testTCAP:test_asn1config(); _ -> ok end. testDER(Config) -> test(Config, fun testDER/3, [ber]). testDER(Config, Rule, Opts) -> asn1_test_lib:compile("DERSpec", Config, [Rule, der|Opts]), testDER:test(). specialized_decodes(Config) -> test(Config, fun specialized_decodes/3, [ber]). specialized_decodes(Config, Rule, Opts) -> asn1_test_lib:compile_all(["PartialDecSeq.asn", "PartialDecSeq2.asn", "PartialDecSeq3.asn", "PartialDecMyHTTP.asn", "MEDIA-GATEWAY-CONTROL.asn", "P-Record", "PartialDecChoExtension.asn"], Config, [Rule,legacy_erlang_types,asn1config|Opts]), test_partial_incomplete_decode:test(Config), test_selective_decode:test(). special_decode_performance(Config) -> test(Config, fun special_decode_performance/3, [ber]). special_decode_performance(Config, Rule, Opts) -> Files = ["MEDIA-GATEWAY-CONTROL", "PartialDecSeq"], asn1_test_lib:compile_all(Files, Config, [Rule, asn1config|Opts]), test_special_decode_performance:go(all). test_ParamTypeInfObj(Config) -> asn1_test_lib:compile("IN-CS-1-Datatypes", Config, [ber]). test_WS_ParamClass(Config) -> test(Config, fun test_WS_ParamClass/3). test_WS_ParamClass(Config, Rule, Opts) -> asn1_test_lib:compile("InformationFramework", Config, [Rule|Opts]), ?only_ber(testWSParamClass:main(Rule)), ok. test_Defed_ObjectIdentifier(Config) -> test(Config, fun test_Defed_ObjectIdentifier/3). test_Defed_ObjectIdentifier(Config, Rule, Opts) -> asn1_test_lib:compile("UsefulDefinitions", Config, [Rule|Opts]). testSelectionType(Config) -> test(Config, fun testSelectionType/3). testSelectionType(Config, Rule, Opts) -> asn1_test_lib:compile("SelectionType", Config, [Rule|Opts]), testSelectionTypes:test(). testSSLspecs(Config) -> test(Config, fun testSSLspecs/3, [ber]). testSSLspecs(Config, Rule, Opts) -> ok = testSSLspecs:compile(Config, [Rule, compact_bit_string, der|Opts]), testSSLspecs:run(Rule), ok = testSSLspecs:compile_combined(Config, Rule), ok = testSSLspecs:run_combined(Rule). testNortel(Config) -> test(Config, fun testNortel/3). testNortel(Config, Rule, Opts) -> asn1_test_lib:compile("Nortel", Config, [Rule|Opts]). test_undecoded_rest(Config) -> test(Config, fun test_undecoded_rest/3). test_undecoded_rest(_Config,jer,_Opts) -> not relevant for JER test_undecoded_rest(Config, Rule, Opts) -> do_test_undecoded_rest(Config, Rule, Opts), do_test_undecoded_rest(Config, Rule, [no_ok_wrapper|Opts]), do_test_undecoded_rest(Config, Rule, [undec_rest|Opts]), do_test_undecoded_rest(Config, Rule, [no_ok_wrapper,undec_rest|Opts]). do_test_undecoded_rest(Config, Rule, Opts) -> asn1_test_lib:compile("P-Record", Config, [Rule|Opts]), test_undecoded_rest:test(Opts, Config). testTcapsystem(Config) -> test(Config, fun testTcapsystem/3). testTcapsystem(Config, Rule, Opts) -> testTcapsystem:compile(Config, [Rule|Opts]). testNBAPsystem(Config) -> test(Config, fun testNBAPsystem/3, [per]). testNBAPsystem(Config, Rule, Opts) -> testNBAPsystem:compile(Config, [Rule|Opts]), testNBAPsystem:test(Rule, Config). testS1AP(Config) -> test(Config, fun testS1AP/3). testS1AP(Config, Rule, Opts) -> S1AP = ["S1AP-CommonDataTypes", "S1AP-Constants", "S1AP-Containers", "S1AP-IEs", "S1AP-PDU-Contents", "S1AP-PDU-Descriptions"], asn1_test_lib:compile_all(S1AP, Config, [Rule|Opts]), case Rule of per -> Enc = <<0,2,64,49,0,0,5,0,0,0,4,128,106,56,197,0,8,0,3,64,2,134,0, 100,64,8,0,66,240,153,0,7,192,16,0,67,64,6,0,66,240,153,70, 1,0,107,64,5,0,0,0,0,0>>, {ok,{initiatingMessage,_}} = 'S1AP-PDU-Descriptions':decode('S1AP-PDU', Enc); uper -> ok; ber -> ok; jer -> ok end. testRfcs() -> [{timetrap,{minutes,90}}]. testRfcs(Config) -> test(Config, fun testRfcs/3, [{ber,[der,?NO_MAPS_MODULE]}, {ber,[der,maps]}]). testRfcs(Config, Rule, Opts) -> case erlang:system_info(system_architecture) of "sparc-sun-solaris2.10" -> {skip,"Too slow for an old Sparc"}; _ -> testRfcs:compile(Config, Rule, Opts), testRfcs:test() end. test_compile_options(Config) -> ok = test_compile_options:wrong_path(Config), ok = test_compile_options:path(Config), ok = test_compile_options:noobj(Config), ok = test_compile_options:record_name_prefix(Config), ok = test_compile_options:verbose(Config), ok = test_compile_options:maps(Config), ok = test_compile_options:determinism(Config). testDoubleEllipses(Config) -> test(Config, fun testDoubleEllipses/3). testDoubleEllipses(Config, Rule, Opts) -> asn1_test_lib:compile("DoubleEllipses", Config, [Rule|Opts]), testDoubleEllipses:main(Rule). test_modified_x420(Config) -> test(Config, fun test_modified_x420/3, [ber]). test_modified_x420(Config, Rule, Opts) -> Files = [filename:join(modified_x420, F) || F <- ["PKCS7", "InformationFramework", "AuthenticationFramework"]], asn1_test_lib:compile_all(Files, Config, [Rule,der|Opts]), test_modified_x420:test(Config). test_x691(Config) -> test(Config, fun test_x691/3, [per, uper]). test_x691(Config, Rule, Opts) -> Files = ["P-RecordA1", "P-RecordA2", "P-RecordA3"], asn1_test_lib:compile_all(Files, Config, [Rule|Opts]), test_x691:cases(Rule), asn1_test_lib:compile("EUTRA-extract-55", Config, [legacy_erlang_types,Rule|Opts]), Val = {'Seq',15,lists:duplicate(8, 0),[0],lists:duplicate(28, 0),15,true}, CompactVal = {'Seq',15,{0,<<0>>},{7,<<0>>},{4,<<0,0,0,0>>},15,true}, {ok,Bin} = 'EUTRA-extract-55':encode('Seq', Val), {ok,Bin} = 'EUTRA-extract-55':encode('Seq', CompactVal), OTP-7678 . asn1_test_lib:compile("UPERDefault", Config, [Rule|Opts]), DefVal = 'UPERDefault':seq(), {ok,DefBin} = 'UPERDefault':encode('Seq', DefVal), {ok,DefVal} = 'UPERDefault':decode('Seq', DefBin), case Rule of uper -> <<0,6,0>> = DefBin; _ -> ok end, ok. ticket_6143(Config) -> asn1_test_lib:compile("AA1", Config, [?NO_MAPS_MODULE]). testExtensionAdditionGroup(Config) -> test(Config, fun testExtensionAdditionGroup/3). testExtensionAdditionGroup(Config, Rule, Opts) -> asn1_test_lib:compile("Extension-Addition-Group", Config, [Rule|Opts]), asn1_test_lib:compile_erlang("extensionAdditionGroup", Config, [debug_info]), asn1_test_lib:compile("EUTRA-RRC-Definitions", Config, [Rule,{record_name_prefix,"RRC-"}|Opts]), extensionAdditionGroup:run(Rule). per_modules() -> [X || X <- test_modules()]. ber_modules() -> [X || X <- test_modules(), X =/= "H323-MESSAGES", X =/= "H235-SECURITY-MESSAGES"]. test_modules() -> ["BitStr", "CAP", "CommonDataTypes", "Constraints", "ContextSwitchingTypes", "CoverParser", "DS-EquipmentUser-CommonFunctionOrig-TransmissionPath", "Enum", "From", "H235-SECURITY-MESSAGES", "H323-MESSAGES", "HighTagNumbers", "Import", "Int", "MAP-commonDataTypes", "Null", "NullTest", "Octetstr", "One", "P-Record", "P", "Person", "PrimStrings", "Real", "XSeq", "XSeqOf", "XSet", "XSetOf", "String", "SwCDR", "Time", must be compiled before Seq and Set "Seq", "Set", "SetOf", "SeqOf", "Prim", "Cho", "Def", "Opt", "ELDAPv3", "LDAP", "SeqOptional2", "CCSNARG3"]. test_OTP_9688(Config) -> PrivDir = proplists:get_value(case_dir, Config), Data = " OTP-9688 DEFINITIONS ::= BEGIN foo INTEGER ::= 1 bar INTEGER ::= 42 Baz ::= INTEGER {x-y-z1(foo), x-y-z2(bar)} Qux ::= SEQUENCE {flerpInfo SEQUENCE {x INTEGER (-10 | -9 | (0..4))} OPTIONAL} END ", File = filename:join(PrivDir, "OTP-9688.asn1"), ok = file:write_file(File, Data), ok = asn1ct:compile(File, [{outdir, PrivDir}]). timer_compile(Config, Opts0) -> Files = ["H235-SECURITY-MESSAGES", "H323-MESSAGES"], Opts = [no_ok_wrapper,?NO_MAPS_MODULE|Opts0], asn1_test_lib:compile_all(Files, Config, Opts). testTimer_ber(Config) -> timer_compile(Config, [ber]), testTimer:go(). testTimer_per(Config) -> timer_compile(Config, [per]), testTimer:go(). testTimer_uper(Config) -> timer_compile(Config, [uper]), testTimer:go(). testTimer_ber_maps(Config) -> timer_compile(Config, [ber,maps]), testTimer:go(). testTimer_per_maps(Config) -> timer_compile(Config, [per,maps]), testTimer:go(). testTimer_uper_maps(Config) -> timer_compile(Config, [uper,maps]), testTimer:go(). Test of multiple - line comment , OTP-8043 testComment(Config) -> asn1_test_lib:compile("Comment", Config, []), asn1_test_lib:roundtrip('Comment', 'Seq', {'Seq',12,true}). testName2Number(Config) -> N2NOptions0 = [{n2n,Type} || Type <- ['Cause-Misc', 'CauseProtocol']], N2NOptions = [?NO_MAPS_MODULE|N2NOptions0], asn1_test_lib:compile("EnumN2N", Config, N2NOptions), 0 = 'EnumN2N':'name2num_Cause-Misc'('control-processing-overload'), 'unknown-PLMN' = 'EnumN2N':'num2name_Cause-Misc'(5), 4 = 'EnumN2N':name2num_CauseProtocol('semantic-error'), 'transfer-syntax-error' = 'EnumN2N':num2name_CauseProtocol(0), N2NOptionsExt = [?NO_MAPS_MODULE,{n2n,'NoExt'},{n2n,'Ext'},{n2n,'Ext2'}], asn1_test_lib:compile("EnumN2N", Config, N2NOptionsExt), 0 = 'EnumN2N':name2num_NoExt('blue'), 2 = 'EnumN2N':name2num_NoExt('green'), blue = 'EnumN2N':num2name_NoExt(0), green = 'EnumN2N':num2name_NoExt(2), 7 = 'EnumN2N':name2num_Ext2('orange'), orange = 'EnumN2N':num2name_Ext2(7), 7 is not defined in Ext , only in Ext2 . {asn1_enum, 7} = 'EnumN2N':num2name_Ext(7), 7 = 'EnumN2N':name2num_Ext({asn1_enum, 7}), 42 = 'EnumN2N':name2num_Ext2({asn1_enum, 42}), ok. ticket_7407(Config) -> Opts = [uper,?NO_MAPS_MODULE], asn1_test_lib:compile("EUTRA-extract-7407", Config, Opts), ticket_7407_code(true), asn1_test_lib:compile("EUTRA-extract-7407", Config, [no_final_padding|Opts]), ticket_7407_code(false). ticket_7407_code(FinalPadding) -> Msg1 = {Type1,_} = eutra1(msg), {ok,B1} = 'EUTRA-extract-7407':encode(Type1, Msg1), B1 = eutra1(result, FinalPadding), Msg2 = {Type2,_} = eutra2(msg), {ok,B2} = 'EUTRA-extract-7407':encode(Type2, Msg2), B2 = eutra2(result, FinalPadding), ok. eutra1(msg) -> {'BCCH-BCH-Message', {'MasterInformationBlock',<<2#0101:4>>,<<2#1010:4>>, {'PHICH-Configuration',short,ffs},<<2#10100000>>}}. eutra1(result, true) -> <<90,80,0>>; eutra1(result, false) -> <<90,80,0:1>>. eutra2(msg) -> {'BCCH-DL-SCH-Message', {c1, {systemInformation1, {'SystemInformationBlockType1', {'SystemInformationBlockType1_cellAccessRelatedInformation', [{'SystemInformationBlockType1_cellAccessRelatedInformation_plmn-IdentityList_SEQOF', {'PLMN-Identity'},true}, {'SystemInformationBlockType1_cellAccessRelatedInformation_plmn-IdentityList_SEQOF', {'PLMN-Identity'},false}, {'SystemInformationBlockType1_cellAccessRelatedInformation_plmn-IdentityList_SEQOF', {'PLMN-Identity'},true}], {'TrackingAreaCode'}, {'CellIdentity'}, false, true, true, true }, {'SystemInformationBlockType1_cellSelectionInfo',-50}, 24, [{'SystemInformationBlockType1_schedulinInformation_SEQOF', {'SystemInformationBlockType1_schedulinInformation_SEQOF_si-MessageType'}, ms320, {'SystemInformationBlockType1_schedulinInformation_SEQOF_sib-MappingInfo'}}], 0 } } } }. eutra2(result, true) -> 55 5C A5 E0 <<85,92,165,224>>; eutra2(result, false) -> <<85,92,165,14:4>>. -record('InitiatingMessage',{procedureCode,criticality,value}). -record('Iu-ReleaseCommand',{first,second}). ticket7904(Config) -> asn1_test_lib:compile("RANAPextract1", Config, [per]), Val1 = #'InitiatingMessage'{procedureCode=1, criticality=ignore, value=#'Iu-ReleaseCommand'{ first=13, second=true}}, {ok,_} = 'RANAPextract1':encode('InitiatingMessage', Val1), {ok,_} = 'RANAPextract1':encode('InitiatingMessage', Val1). xref(_Config) -> S = ?FUNCTION_NAME, xref:start(S), xref:set_default(S, [{verbose,false},{warnings,false},{builtins,true}]), Test = filename:dirname(code:which(?MODULE)), {ok,_PMs} = xref:add_directory(S, Test), Q = "X - XU - \".*_SUITE\" : Mod", UnusedExports = xref:q(S, Q), xref:stop(S), case UnusedExports of {ok,[]} -> ok; {ok,[_|_]=Res} -> ct:fail("Exported, but unused: ~p\n", [Res]) end. xref_export_all(_Config) -> S = ?FUNCTION_NAME, xref:start(S), xref:set_default(S, [{verbose,false},{warnings,false},{builtins,true}]), {ok,_PMs} = xref:add_module(S, code:which(?MODULE)), AllCalled = all_called(), Def = "Called := " ++ lists:flatten(io_lib:format("~p", [AllCalled])), {ok,_} = xref:q(S, Def), {ok,Unused} = xref:q(S, "X - Called - range (closure E | Called)"), xref:stop(S), case Unused -- [{?MODULE,otp_14440_decode,0}] of [] -> ok; [_|_] -> Msg = [io_lib:format("~p:~p/~p\n", [M,F,A]) || {M,F,A} <- Unused], ct:fail("There are unused functions:\n\n~s\n", [Msg]) end. all_called() -> [{?MODULE,end_per_group,2}, {?MODULE,end_per_suite,1}, {?MODULE,end_per_testcase,2}, {?MODULE,init_per_group,2}, {?MODULE,init_per_suite,1}, {?MODULE,init_per_testcase,2}, {?MODULE,suite,0}] ++ all_called_1(all() ++ groups()). all_called_1([{_,_}|T]) -> all_called_1(T); all_called_1([{_Name,_Flags,Fs}|T]) -> all_called_1(Fs ++ T); all_called_1([F|T]) when is_atom(F) -> L = case erlang:function_exported(?MODULE, F, 0) of false -> [{?MODULE,F,1}]; true -> [{?MODULE,F,0},{?MODULE,F,1}] end, L ++ all_called_1(T); all_called_1([]) -> [].
f16e0c3431a65b21ada299dd6e103017edae0579783d6bd4e5508bb3c60b5205
ocaml-multicore/tezos
injection.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2018 Nomadic Labs , < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) open Protocol open Alpha_context open Apply_results open Protocol_client_context Under normal network conditions and an attacker with less than 33 % of stake , an operation can be considered final with quasi - certainty if there are at least 5 blocks built on top of it . See Emmy * TZIP for more detailed explanations . than 33% of stake, an operation can be considered final with quasi-certainty if there are at least 5 blocks built on top of it. See Emmy* TZIP for more detailed explanations. *) let num_confirmation_blocks = 5 let get_branch (rpc_config : #Protocol_client_context.full) ~chain ~(block : Block_services.block) branch = let branch = Option.value ~default:0 branch in (* TODO export parameter *) (match block with | `Head n -> return (`Head (n + branch)) | `Hash (h, n) -> return (`Hash (h, n + branch)) | `Alias (a, n) -> return (`Alias (a, n)) | `Genesis -> return `Genesis | `Level i -> return (`Level i)) >>=? fun block -> Shell_services.Blocks.hash rpc_config ~chain ~block () >>=? fun hash -> Shell_services.Chain.chain_id rpc_config ~chain () >>=? fun chain_id -> return (chain_id, hash) type 'kind preapply_result = Operation_hash.t * 'kind operation * 'kind operation_metadata type 'kind result_list = Operation_hash.t * 'kind contents_list * 'kind contents_result_list type 'kind result = Operation_hash.t * 'kind contents * 'kind contents_result let get_manager_operation_gas_and_fee contents = let open Operation in let l = to_list (Contents_list contents) in List.fold_left (fun acc -> function | Contents (Manager_operation {fee; gas_limit; _}) -> ( match acc with | Error _ as e -> e | Ok (total_fee, total_gas) -> ( match Tez.(total_fee +? fee) with | Ok total_fee -> Ok (total_fee, Gas.Arith.add total_gas gas_limit) | Error _ as e -> e)) | _ -> acc) (Ok (Tez.zero, Gas.Arith.zero)) l type fee_parameter = { minimal_fees : Tez.t; minimal_nanotez_per_byte : Q.t; minimal_nanotez_per_gas_unit : Q.t; force_low_fee : bool; fee_cap : Tez.t; burn_cap : Tez.t; } let dummy_fee_parameter = { minimal_fees = Tez.zero; minimal_nanotez_per_byte = Q.zero; minimal_nanotez_per_gas_unit = Q.zero; force_low_fee = false; fee_cap = Tez.one; burn_cap = Tez.zero; } (* Rounding up (see Z.cdiv) *) let z_mutez_of_q_nanotez (ntz : Q.t) = let q_mutez = Q.div ntz (Q.of_int 1000) in Z.cdiv q_mutez.Q.num q_mutez.Q.den let check_fees : type t. #Protocol_client_context.full -> fee_parameter -> t contents_list -> int -> unit Lwt.t = fun cctxt config op size -> match get_manager_operation_gas_and_fee op with FIXME | Ok (fee, gas) -> if Tez.compare fee config.fee_cap > 0 then cctxt#error "The proposed fee (%s%a) are higher than the configured fee cap \ (%s%a).@\n\ \ Use `--fee-cap %a` to emit this operation anyway." Client_proto_args.tez_sym Tez.pp fee Client_proto_args.tez_sym Tez.pp config.fee_cap Tez.pp fee >>= fun () -> exit 1 else let fees_in_nanotez = Q.mul (Q.of_int64 (Tez.to_mutez fee)) (Q.of_int 1000) in let minimal_fees_in_nanotez = Q.mul (Q.of_int64 (Tez.to_mutez config.minimal_fees)) (Q.of_int 1000) in let minimal_fees_for_gas_in_nanotez = Q.mul config.minimal_nanotez_per_gas_unit (Q.of_bigint (Gas.Arith.integral_to_z gas)) in let minimal_fees_for_size_in_nanotez = Q.mul config.minimal_nanotez_per_byte (Q.of_int size) in let estimated_fees_in_nanotez = Q.add minimal_fees_in_nanotez (Q.add minimal_fees_for_gas_in_nanotez minimal_fees_for_size_in_nanotez) in let estimated_fees_in_mutez = z_mutez_of_q_nanotez estimated_fees_in_nanotez in let estimated_fees = match Tez.of_mutez (Z.to_int64 estimated_fees_in_mutez) with | None -> assert false | Some fee -> fee in if (not config.force_low_fee) && Q.compare fees_in_nanotez estimated_fees_in_nanotez < 0 then cctxt#error "The proposed fee (%s%a) are lower than the fee that baker expect \ by default (%s%a).@\n\ \ Use `--force-low-fee` to emit this operation anyway." Client_proto_args.tez_sym Tez.pp fee Client_proto_args.tez_sym Tez.pp estimated_fees >>= fun () -> exit 1 else Lwt.return_unit let print_for_verbose_signing ppf ~watermark ~bytes ~branch ~contents = let open Format in pp_open_vbox ppf 0 ; let item f = pp_open_hovbox ppf 4 ; pp_print_string ppf " * " ; f ppf () ; pp_close_box ppf () ; pp_print_cut ppf () in let hash_pp l = fprintf ppf "%s" (Base58.raw_encode Blake2B.(hash_bytes l |> to_string)) in item (fun ppf () -> pp_print_text ppf "Branch: " ; Block_hash.pp ppf branch) ; item (fun ppf () -> fprintf ppf "Watermark: `%a` (0x%s)" Signature.pp_watermark watermark (Hex.of_bytes (Signature.bytes_of_watermark watermark) |> Hex.show)) ; item (fun ppf () -> pp_print_text ppf "Operation bytes: " ; TzString.fold_left (* We split the bytes into lines for display: *) (fun n c -> pp_print_char ppf c ; if n < 72 (* is the email-body standard width, ideal for copy-pasting. *) then n + 1 else ( pp_print_space ppf () ; 0)) 0 (Hex.of_bytes bytes |> Hex.show) |> ignore) ; item (fun ppf () -> pp_print_text ppf "Blake 2B Hash (raw): " ; hash_pp [bytes]) ; item (fun ppf () -> pp_print_text ppf "Blake 2B Hash (ledger-style, with operation watermark): " ; hash_pp [Signature.bytes_of_watermark watermark; bytes]) ; let json = Data_encoding.Json.construct Operation.unsigned_encoding ({branch}, Contents_list contents) in item (fun ppf () -> pp_print_text ppf "JSON encoding: " ; Data_encoding.Json.pp ppf json) ; pp_close_box ppf () let preapply (type t) (cctxt : #Protocol_client_context.full) ~chain ~block ?(verbose_signing = false) ?fee_parameter ?branch ?src_sk (contents : t contents_list) = get_branch cctxt ~chain ~block branch >>=? fun (chain_id, branch) -> let bytes = Data_encoding.Binary.to_bytes_exn Operation.unsigned_encoding ({branch}, Contents_list contents) in (match src_sk with | None -> return_none | Some src_sk -> let watermark = match contents with | Single (Endorsement _) -> Signature.(Endorsement chain_id) | _ -> Signature.Generic_operation in (if verbose_signing then cctxt#message "Pre-signature information (verbose signing):@.%t%!" (print_for_verbose_signing ~watermark ~bytes ~branch ~contents) else Lwt.return_unit) >>= fun () -> Client_keys.sign cctxt ~watermark src_sk bytes >>=? fun signature -> return_some signature) >>=? fun signature -> let op : _ Operation.t = {shell = {branch}; protocol_data = {contents; signature}} in let oph = Operation.hash op in let size = Bytes.length bytes + Signature.size in (match fee_parameter with | Some fee_parameter -> check_fees cctxt fee_parameter contents size | None -> Lwt.return_unit) >>= fun () -> Protocol_client_context.Alpha_block_services.Helpers.Preapply.operations cctxt ~chain ~block [Operation.pack op] >>=? function | [(Operation_data op', Operation_metadata result)] -> ( match ( Operation.equal op {shell = {branch}; protocol_data = op'}, Apply_results.kind_equal_list contents result.contents ) with | (Some Operation.Eq, Some Apply_results.Eq) -> return ((oph, op, result) : t preapply_result) | _ -> failwith "Unexpected result") | _ -> failwith "Unexpected result" let simulate (type t) (cctxt : #Protocol_client_context.full) ~chain ~block ?branch ?(latency = Plugin.default_operation_inclusion_latency) (contents : t contents_list) = get_branch cctxt ~chain ~block branch >>=? fun (_chain_id, branch) -> let op : _ Operation.t = {shell = {branch}; protocol_data = {contents; signature = None}} in let oph = Operation.hash op in Chain_services.chain_id cctxt ~chain () >>=? fun chain_id -> Plugin.RPC.Scripts.simulate_operation cctxt (chain, block) ~op:(Operation.pack op) ~chain_id ~latency >>=? function | (Operation_data op', Operation_metadata result) -> ( match ( Operation.equal op {shell = {branch}; protocol_data = op'}, Apply_results.kind_equal_list contents result.contents ) with | (Some Operation.Eq, Some Apply_results.Eq) -> return ((oph, op, result) : t preapply_result) | _ -> failwith "Unexpected result") | _ -> failwith "Unexpected result" let estimated_gas_single (type kind) (Manager_operation_result {operation_result; internal_operation_results; _} : kind Kind.manager contents_result) = let consumed_gas (type kind) (result : kind manager_operation_result) = match result with | Applied (Transaction_result {consumed_gas; _}) -> Ok consumed_gas | Applied (Origination_result {consumed_gas; _}) -> Ok consumed_gas | Applied (Reveal_result {consumed_gas}) -> Ok consumed_gas | Applied (Delegation_result {consumed_gas}) -> Ok consumed_gas | Applied (Register_global_constant_result {consumed_gas; _}) -> Ok consumed_gas | Skipped _ -> assert false | Backtracked (_, None) -> Ok Gas.Arith.zero (* there must be another error for this to happen *) | Backtracked (_, Some errs) -> Error (Environment.wrap_tztrace errs) | Failed (_, errs) -> Error (Environment.wrap_tztrace errs) in consumed_gas operation_result >>? fun acc -> List.fold_left_e (fun acc (Internal_operation_result (_, r)) -> consumed_gas r >>? fun gas -> Ok (Gas.Arith.add acc gas)) acc internal_operation_results let estimated_storage_single (type kind) origination_size (Manager_operation_result {operation_result; internal_operation_results; _} : kind Kind.manager contents_result) = let storage_size_diff (type kind) (result : kind manager_operation_result) = match result with | Applied (Transaction_result {paid_storage_size_diff; allocated_destination_contract; _}) -> if allocated_destination_contract then Ok (Z.add paid_storage_size_diff origination_size) else Ok paid_storage_size_diff | Applied (Origination_result {paid_storage_size_diff; _}) -> Ok (Z.add paid_storage_size_diff origination_size) | Applied (Reveal_result _) -> Ok Z.zero | Applied (Delegation_result _) -> Ok Z.zero | Applied (Register_global_constant_result {size_of_constant; _}) -> Ok size_of_constant | Skipped _ -> assert false | Backtracked (_, None) -> Ok Z.zero (* there must be another error for this to happen *) | Backtracked (_, Some errs) -> Error (Environment.wrap_tztrace errs) | Failed (_, errs) -> Error (Environment.wrap_tztrace errs) in storage_size_diff operation_result >>? fun acc -> List.fold_left_e (fun acc (Internal_operation_result (_, r)) -> storage_size_diff r >>? fun storage -> Ok (Z.add acc storage)) acc internal_operation_results let estimated_storage origination_size res = let rec estimated_storage : type kind. kind contents_result_list -> _ = function | Single_result (Manager_operation_result _ as res) -> estimated_storage_single origination_size res | Single_result _ -> Ok Z.zero | Cons_result (res, rest) -> estimated_storage_single origination_size res >>? fun storage1 -> estimated_storage rest >>? fun storage2 -> Ok (Z.add storage1 storage2) in estimated_storage res >>? fun diff -> Ok (Z.max Z.zero diff) let originated_contracts_single (type kind) (Manager_operation_result {operation_result; internal_operation_results; _} : kind Kind.manager contents_result) = let originated_contracts (type kind) (result : kind manager_operation_result) = match result with | Applied (Transaction_result {originated_contracts; _}) -> Ok originated_contracts | Applied (Origination_result {originated_contracts; _}) -> Ok originated_contracts | Applied (Register_global_constant_result _) -> Ok [] | Applied (Reveal_result _) -> Ok [] | Applied (Delegation_result _) -> Ok [] | Skipped _ -> assert false | Backtracked (_, None) -> Ok [] (* there must be another error for this to happen *) | Backtracked (_, Some errs) -> Error (Environment.wrap_tztrace errs) | Failed (_, errs) -> Error (Environment.wrap_tztrace errs) in originated_contracts operation_result >>? fun acc -> let acc = List.rev acc in List.fold_left_e (fun acc (Internal_operation_result (_, r)) -> originated_contracts r >>? fun contracts -> Ok (List.rev_append contracts acc)) acc internal_operation_results let rec originated_contracts : type kind. kind contents_result_list -> _ = function | Single_result (Manager_operation_result _ as res) -> originated_contracts_single res >|? List.rev | Single_result _ -> Ok [] | Cons_result (res, rest) -> originated_contracts_single res >>? fun contracts1 -> originated_contracts rest >>? fun contracts2 -> Ok (List.rev_append contracts1 contracts2) (* When --force is used, we don't want [originated_contracts] to fail as it would stop the client before the injection of the operation. *) let originated_contracts ~force results = match originated_contracts results with Error _ when force -> Ok [] | e -> e let detect_script_failure : type kind. kind operation_metadata -> _ = let rec detect_script_failure : type kind. kind contents_result_list -> _ = let detect_script_failure_single (type kind) (Manager_operation_result {operation_result; internal_operation_results; _} : kind Kind.manager contents_result) = let detect_script_failure (type kind) (result : kind manager_operation_result) = match result with | Applied _ -> Ok () | Skipped _ -> assert false | Backtracked (_, None) -> (* there must be another error for this to happen *) Ok () | Backtracked (_, Some errs) -> record_trace (error_of_fmt "The transfer simulation failed.") (Error (Environment.wrap_tztrace errs)) | Failed (_, errs) -> record_trace (error_of_fmt "The transfer simulation failed.") (Error (Environment.wrap_tztrace errs)) in detect_script_failure operation_result >>? fun () -> List.iter_e (fun (Internal_operation_result (_, r)) -> detect_script_failure r) internal_operation_results in function | Single_result (Manager_operation_result _ as res) -> detect_script_failure_single res | Single_result _ -> Ok () | Cons_result (res, rest) -> detect_script_failure_single res >>? fun () -> detect_script_failure rest in fun {contents} -> detect_script_failure contents (* This value is used as a safety guard for gas limit. *) let safety_guard = Gas.Arith.(integral_of_int_exn 100) { 2 High - level description of the automatic gas patching algorithm } When the user wants to inject a list of operations , some of which might have unspecified gas , fees or storage limit , the client performs a { e simulation } to estimate those limits and assign sensible values to them . The simulation works as follows : 1 . limits are assigned to dummy , high values to ensure that the operations can be simulated - 1.a ) when a list of operations is partially specified , the algorithm allocates to each unspecified operation an equal portion of the maximum gas per block minus the gas consumed by the operations that do specify their limit 2 . the algorithm retrieves the effectively consumed gas and storage from the receipt 3 . the algorithm assigns slight overapproximations to the operation 4 . a default fee is computed and set {2 High-level description of the automatic gas patching algorithm} When the user wants to inject a list of operations, some of which might have unspecified gas, fees or storage limit, the client performs a {e simulation} to estimate those limits and assign sensible values to them. The simulation works as follows: 1. limits are assigned to dummy, high values to ensure that the operations can be simulated - 1.a) when a list of operations is partially specified, the algorithm allocates to each unspecified operation an equal portion of the maximum gas per block minus the gas consumed by the operations that do specify their limit 2. the algorithm retrieves the effectively consumed gas and storage from the receipt 3. the algorithm assigns slight overapproximations to the operation 4. a default fee is computed and set *) let may_patch_limits (type kind) (cctxt : #Protocol_client_context.full) ~fee_parameter ~chain ~block ?branch (annotated_contents : kind Annotated_manager_operation.annotated_list) : kind Kind.manager contents_list tzresult Lwt.t = Tezos_client_base.Client_confirmations.wait_for_bootstrapped cctxt >>=? fun () -> Alpha_services.Constants.all cctxt (chain, block) >>=? fun { parametric = { hard_gas_limit_per_operation; hard_gas_limit_per_block; hard_storage_limit_per_operation; origination_size; cost_per_byte; _; }; _; } -> let user_gas_limit_needs_patching user_gas_limit = Limit.fold user_gas_limit ~unknown:true ~known:(fun user_gas_limit -> Gas.Arith.( user_gas_limit < zero || hard_gas_limit_per_operation < user_gas_limit)) in let user_storage_limit_needs_patching user_storage_limit = Limit.fold user_storage_limit ~unknown:true ~known:(fun user_storage_limit -> Z.Compare.( user_storage_limit < Z.zero || hard_storage_limit_per_operation < user_storage_limit)) in let gas_patching_stats (Annotated_manager_operation.Manager_info c) need_patching gas_consumed = if user_gas_limit_needs_patching c.gas_limit then (need_patching + 1, gas_consumed) else ( need_patching, Gas.Arith.add gas_consumed (Limit.value ~when_unknown:Gas.Arith.zero c.gas_limit) ) in let rec gas_patching_stats_list : type kind. kind Annotated_manager_operation.annotated_list -> int -> Saturation_repr.may_saturate Saturation_repr.t -> int * Saturation_repr.may_saturate Saturation_repr.t = fun op need_patching gas_consumed -> match op with | Single_manager minfo -> gas_patching_stats minfo need_patching gas_consumed | Cons_manager (minfo, rest) -> let (need_patching, gas_consumed) = gas_patching_stats minfo need_patching gas_consumed in gas_patching_stats_list rest need_patching gas_consumed in let may_need_patching_single : type kind. Gas.Arith.integral -> kind Annotated_manager_operation.t -> kind Annotated_manager_operation.t option = fun gas_limit_per_patched_op op -> match op with | Manager_info c -> let needs_patching = Limit.is_unknown c.fee || user_gas_limit_needs_patching c.gas_limit || user_storage_limit_needs_patching c.storage_limit in if not needs_patching then None else (* Set limits for simulation purposes *) let gas_limit = if user_gas_limit_needs_patching c.gas_limit then Limit.known gas_limit_per_patched_op else c.gas_limit in let storage_limit = if user_storage_limit_needs_patching c.storage_limit then Limit.known hard_storage_limit_per_operation else c.storage_limit in let fee = Limit.value ~when_unknown:Tez.zero c.fee in Some (Manager_info {c with gas_limit; storage_limit; fee = Limit.known fee}) in let may_need_patching gas_limit_per_patched_op ops = let rec loop : type kind. kind Annotated_manager_operation.annotated_list -> kind Annotated_manager_operation.annotated_list option = function | Single_manager annotated_op -> Option.map (fun op -> Annotated_manager_operation.Single_manager op) @@ may_need_patching_single gas_limit_per_patched_op annotated_op | Cons_manager (annotated_op, rest) -> ( let annotated_op_opt = may_need_patching_single gas_limit_per_patched_op annotated_op in let rest_opt = loop rest in match (annotated_op_opt, rest_opt) with | (None, None) -> None | _ -> let op = Option.value ~default:annotated_op annotated_op_opt in let rest = Option.value ~default:rest rest_opt in Some (Cons_manager (op, rest))) in loop ops in (* The recursion here handles the case where an increased fee might increase the size of the operation, and so require a recalculation of the gas costs. Rationale for termination: - the fee for size increases linearly with the size of the operation. - however, when the size of the operation increase to make space for an increased fee, the amount of new fee that can be added without increasing the size of the block again increases exponentially. - hence, there will eventually be a increase of size that will fit any new fee without having to increase the size of the operation again. *) let rec patch_fee : type kind. first:bool -> kind contents -> kind contents = fun ~first -> function | Manager_operation c as op -> ( let size = if first then (WithExceptions.Option.get ~loc:__LOC__ @@ Data_encoding.Binary.fixed_length Tezos_base.Operation.shell_header_encoding) + Data_encoding.Binary.length Operation.contents_encoding (Contents op) + Signature.size else Data_encoding.Binary.length Operation.contents_encoding (Contents op) in let minimal_fees_in_nanotez = Q.mul (Q.of_int64 (Tez.to_mutez fee_parameter.minimal_fees)) (Q.of_int 1000) in let minimal_fees_for_gas_in_nanotez = Q.mul fee_parameter.minimal_nanotez_per_gas_unit (Q.of_bigint @@ Gas.Arith.integral_to_z c.gas_limit) in let minimal_fees_for_size_in_nanotez = Q.mul fee_parameter.minimal_nanotez_per_byte (Q.of_int size) in let fees_in_nanotez = Q.add minimal_fees_in_nanotez @@ Q.add minimal_fees_for_gas_in_nanotez minimal_fees_for_size_in_nanotez in let fees_in_mutez = z_mutez_of_q_nanotez fees_in_nanotez in match Tez.of_mutez (Z.to_int64 fees_in_mutez) with | None -> assert false | Some fee -> if Tez.(fee <= c.fee) then op else patch_fee ~first (Manager_operation {c with fee})) | c -> c in let patch : type kind. first:bool -> kind Annotated_manager_operation.t * kind Kind.manager contents_result -> kind Kind.manager contents tzresult Lwt.t = fun ~first -> function | ((Manager_info c as op), (Manager_operation_result _ as result)) -> (if user_gas_limit_needs_patching c.gas_limit then Lwt.return (estimated_gas_single result) >>=? fun gas -> if Gas.Arith.(gas = zero) then cctxt#message "Estimated gas: none" >>= fun () -> return (Annotated_manager_operation.set_gas_limit (Limit.known Gas.Arith.zero) op) else cctxt#message "Estimated gas: %a units (will add 100 for safety)" Gas.Arith.pp gas >>= fun () -> let safe_gas = Gas.Arith.(add (ceil gas) safety_guard) in let patched_gas = Gas.Arith.min safe_gas hard_gas_limit_per_operation in return (Annotated_manager_operation.set_gas_limit (Limit.known patched_gas) op) else return op) >>=? fun op -> (if user_storage_limit_needs_patching c.storage_limit then Lwt.return (estimated_storage_single (Z.of_int origination_size) result) >>=? fun storage -> if Z.equal storage Z.zero then cctxt#message "Estimated storage: no bytes added" >>= fun () -> return (Annotated_manager_operation.set_storage_limit (Limit.known Z.zero) op) else cctxt#message "Estimated storage: %s bytes added (will add 20 for safety)" (Z.to_string storage) >>= fun () -> let storage_limit = Z.min (Z.add storage (Z.of_int 20)) hard_storage_limit_per_operation in return (Annotated_manager_operation.set_storage_limit (Limit.known storage_limit) op) else return op) >>=? fun op -> if Limit.is_unknown c.fee then (* Setting a dummy fee is required for converting to manager op *) let op = Annotated_manager_operation.set_fee (Limit.known Tez.zero) op in Annotated_manager_operation.manager_from_annotated op >>?= fun cm -> return (patch_fee ~first cm) else Lwt.return (Annotated_manager_operation.manager_from_annotated op) in let rec patch_list : type kind. bool -> kind Annotated_manager_operation.annotated_list -> kind Kind.manager contents_result_list -> kind Kind.manager contents_list tzresult Lwt.t = fun first annotated_list result_list -> match (annotated_list, result_list) with | (Single_manager annotated, Single_result res) -> patch ~first (annotated, res) >>=? fun op -> return (Single op) | (Cons_manager (annotated, annotated_rest), Cons_result (res, res_rest)) -> patch ~first (annotated, res) >>=? fun op -> patch_list false annotated_rest res_rest >>=? fun rest -> return (Cons (op, rest)) | _ -> assert false in let gas_limit_per_patched_op = let (need_gas_patching, gas_consumed) = gas_patching_stats_list annotated_contents 0 Gas.Arith.zero in if need_gas_patching = 0 then hard_gas_limit_per_operation else let remaining_gas = Gas.Arith.sub hard_gas_limit_per_block gas_consumed in let average_per_operation_gas = Gas.Arith.integral_exn @@ Z.div (Gas.Arith.integral_to_z remaining_gas) (Z.of_int need_gas_patching) in Gas.Arith.min hard_gas_limit_per_operation average_per_operation_gas in match may_need_patching gas_limit_per_patched_op annotated_contents with | Some annotated_for_simulation -> Lwt.return (Annotated_manager_operation.manager_list_from_annotated annotated_for_simulation) >>=? fun contents_for_simulation -> simulate cctxt ~chain ~block ?branch contents_for_simulation >>=? fun (_, _, result) -> (match detect_script_failure result with | Ok () -> return_unit | Error _ -> cctxt#message "@[<v 2>This simulation failed:@,%a@]" Operation_result.pp_operation_result (contents_for_simulation, result.contents) >>= fun () -> return_unit) >>=? fun () -> ( Lwt.return (estimated_storage (Z.of_int origination_size) result.contents) >>=? fun storage -> Lwt.return (Environment.wrap_tzresult Tez.(cost_per_byte *? Z.to_int64 storage)) >>=? fun burn -> if Tez.(burn > fee_parameter.burn_cap) then cctxt#error "The operation will burn %s%a which is higher than the configured \ burn cap (%s%a).@\n\ \ Use `--burn-cap %a` to emit this operation." Client_proto_args.tez_sym Tez.pp burn Client_proto_args.tez_sym Tez.pp fee_parameter.burn_cap Tez.pp burn >>= fun () -> exit 1 else return_unit ) >>=? fun () -> patch_list true annotated_contents result.contents | None -> Lwt.return (Annotated_manager_operation.manager_list_from_annotated annotated_contents) let inject_operation_internal (type kind) cctxt ~chain ~block ?confirmations ?(dry_run = false) ?(simulation = false) ?(force = false) ?branch ?src_sk ?verbose_signing ~fee_parameter (contents : kind contents_list) = (if simulation then simulate cctxt ~chain ~block ?branch contents else preapply cctxt ~chain ~block ~fee_parameter ?verbose_signing ?branch ?src_sk contents) >>=? fun (_oph, op, result) -> (match detect_script_failure result with | Ok () -> return_unit | Error _ as res -> cctxt#message "@[<v 2>This simulation failed:@,%a@]" Operation_result.pp_operation_result (op.protocol_data.contents, result.contents) >>= fun () -> if force then return_unit else Lwt.return res) >>=? fun () -> let bytes = Data_encoding.Binary.to_bytes_exn Operation.encoding (Operation.pack op) in if dry_run || simulation then let oph = Operation_hash.hash_bytes [bytes] in cctxt#message "@[<v 0>Operation: 0x%a@,Operation hash is '%a'@]" Hex.pp (Hex.of_bytes bytes) Operation_hash.pp oph >>= fun () -> cctxt#message "@[<v 2>Simulation result:@,%a@]" Operation_result.pp_operation_result (op.protocol_data.contents, result.contents) >>= fun () -> return (oph, op.protocol_data.contents, result.contents) else Shell_services.Injection.operation cctxt ~chain bytes >>=? fun oph -> cctxt#message "Operation successfully injected in the node." >>= fun () -> cctxt#message "Operation hash is '%a'" Operation_hash.pp oph >>= fun () -> (match confirmations with | None -> cctxt#message "@[<v 0>NOT waiting for the operation to be included.@,\ Use command@,\ \ tezos-client wait for %a to be included --confirmations %d \ --branch %a@,\ and/or an external block explorer to make sure that it has been \ included.@]" Operation_hash.pp oph num_confirmation_blocks Block_hash.pp op.shell.branch >>= fun () -> return result | Some confirmations -> ( cctxt#message "Waiting for the operation to be included..." >>= fun () -> Client_confirmations.wait_for_operation_inclusion ~branch:op.shell.branch ~confirmations cctxt ~chain oph >>=? fun (h, i, j) -> Alpha_block_services.Operations.operation cctxt ~chain ~block:(`Hash (h, 0)) i j >>=? fun op' -> match op'.receipt with | None -> failwith "Internal error: pruned metadata." | Some No_operation_metadata -> failwith "Internal error: unexpected receipt." | Some (Operation_metadata receipt) -> ( match Apply_results.kind_equal_list contents receipt.contents with | Some Apply_results.Eq -> return (receipt : kind operation_metadata) | None -> failwith "Internal error: unexpected receipt."))) >>=? fun result -> cctxt#message "@[<v 2>This sequence of operations was run:@,%a@]" Operation_result.pp_operation_result (op.protocol_data.contents, result.contents) >>= fun () -> Lwt.return (originated_contracts result.contents ~force) >>=? fun contracts -> List.iter_s (fun c -> cctxt#message "New contract %a originated." Contract.pp c) contracts >>= fun () -> (match confirmations with | None -> Lwt.return_unit | Some number -> if number >= num_confirmation_blocks then cctxt#message "The operation was included in a block %d blocks ago." number else cctxt#message "@[<v 0>The operation has only been included %d blocks ago.@,\ We recommend to wait more.@,\ Use command@,\ \ tezos-client wait for %a to be included --confirmations %d \ --branch %a@,\ and/or an external block explorer.@]" number Operation_hash.pp oph num_confirmation_blocks Block_hash.pp op.shell.branch) >>= fun () -> return (oph, op.protocol_data.contents, result.contents) let inject_operation (type kind) cctxt ~chain ~block ?confirmations ?(dry_run = false) ?(simulation = false) ?branch ?src_sk ?verbose_signing ~fee_parameter (contents : kind contents_list) = Tezos_client_base.Client_confirmations.wait_for_bootstrapped cctxt >>=? fun () -> inject_operation_internal cctxt ~chain ~block ?confirmations ~dry_run ~simulation ?branch ?src_sk ?verbose_signing ~fee_parameter (contents : kind contents_list) let prepare_manager_operation ~fee ~gas_limit ~storage_limit operation = Annotated_manager_operation.Manager_info {source = None; fee; gas_limit; storage_limit; counter = None; operation} (* [gas_limit] must correspond to [Michelson_v1_gas.Cost_of.manager_operation] *) let cost_of_manager_operation = Gas.Arith.integral_of_int_exn 1_000 let reveal_error_message = "Requested operation requires to perform a public key revelation beforehand.\n\ This cannot be done automatically when a custom fee or storage limit is \ given.\n\ If you wish to use a custom fee or storage limit, please first perform the \ reveal operation separately using the dedicated command.\n\ Otherwise, please do not specify custom fee or storage parameters." let reveal_error (cctxt : #Protocol_client_context.full) = cctxt#error "%s" reveal_error_message let inject_manager_operation cctxt ~chain ~block ?branch ?confirmations ?dry_run ?verbose_signing ?simulation ?force ~source ~src_pk ~src_sk ~fee ~gas_limit ~storage_limit ?counter ~fee_parameter (type kind) (operations : kind Annotated_manager_operation.annotated_list) : (Operation_hash.t * kind Kind.manager contents_list * kind Kind.manager contents_result_list) tzresult Lwt.t = (match counter with | None -> Alpha_services.Contract.counter cctxt (chain, block) source >>=? fun pcounter -> let counter = Z.succ pcounter in return counter | Some counter -> return counter) >>=? fun counter -> Alpha_services.Contract.manager_key cctxt (chain, block) source >>=? fun key -> [ has_reveal ] assumes that a Reveal operation only appears as the first of a batch let has_reveal : type kind. kind Annotated_manager_operation.annotated_list -> bool = function | Single_manager (Manager_info {operation = Reveal _; _}) -> true | Cons_manager (Manager_info {operation = Reveal _; _}, _) -> true | _ -> false in let apply_specified_options counter op = Annotated_manager_operation.set_source source op >>? fun op -> Annotated_manager_operation.set_counter counter op >>? fun op -> Annotated_manager_operation.join_fee fee op >>? fun op -> Annotated_manager_operation.join_gas_limit gas_limit op >>? fun op -> Annotated_manager_operation.join_storage_limit storage_limit op in let rec build_contents : type kind. Z.t -> kind Annotated_manager_operation.annotated_list -> kind Annotated_manager_operation.annotated_list tzresult = fun counter -> function | Single_manager op -> apply_specified_options counter op >|? fun op -> Annotated_manager_operation.Single_manager op | Cons_manager (op, rest) -> apply_specified_options counter op >>? fun op -> build_contents (Z.succ counter) rest >|? fun rest -> Annotated_manager_operation.Cons_manager (op, rest) in match key with | None when not (has_reveal operations) -> ( (if not (Limit.is_unknown fee && Limit.is_unknown storage_limit) then reveal_error cctxt else return_unit) >>=? fun () -> let reveal = prepare_manager_operation ~fee:Limit.unknown ~gas_limit:(Limit.known cost_of_manager_operation) ~storage_limit:Limit.unknown (Reveal src_pk) in Annotated_manager_operation.set_source source reveal >>?= fun reveal -> Annotated_manager_operation.set_counter counter reveal >>?= fun reveal -> build_contents (Z.succ counter) operations >>?= fun rest -> let contents = Annotated_manager_operation.Cons_manager (reveal, rest) in may_patch_limits cctxt ~fee_parameter ~chain ~block ?branch contents >>=? fun contents -> inject_operation_internal cctxt ~chain ~block ?confirmations ?dry_run ?simulation ?force ~fee_parameter ?verbose_signing ?branch ~src_sk contents >>=? fun (oph, op, result) -> match pack_contents_list op result with | Cons_and_result (_, _, rest) -> let (op, result) = unpack_contents_list rest in return (oph, op, result) | _ -> assert false) | Some _ when has_reveal operations -> failwith "The manager key was previously revealed." | _ -> build_contents counter operations >>?= fun contents -> may_patch_limits cctxt ~fee_parameter ~chain ~block ?branch contents >>=? fun contents -> inject_operation_internal cctxt ~chain ~block ?confirmations ?dry_run ?verbose_signing ?simulation ?force ~fee_parameter ?branch ~src_sk contents
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_011_PtHangz2/lib_client/injection.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. *************************************************************************** TODO export parameter Rounding up (see Z.cdiv) We split the bytes into lines for display: is the email-body standard width, ideal for copy-pasting. there must be another error for this to happen there must be another error for this to happen there must be another error for this to happen When --force is used, we don't want [originated_contracts] to fail as it would stop the client before the injection of the operation. there must be another error for this to happen This value is used as a safety guard for gas limit. Set limits for simulation purposes The recursion here handles the case where an increased fee might increase the size of the operation, and so require a recalculation of the gas costs. Rationale for termination: - the fee for size increases linearly with the size of the operation. - however, when the size of the operation increase to make space for an increased fee, the amount of new fee that can be added without increasing the size of the block again increases exponentially. - hence, there will eventually be a increase of size that will fit any new fee without having to increase the size of the operation again. Setting a dummy fee is required for converting to manager op [gas_limit] must correspond to [Michelson_v1_gas.Cost_of.manager_operation]
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2018 Nomadic Labs , < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Protocol open Alpha_context open Apply_results open Protocol_client_context Under normal network conditions and an attacker with less than 33 % of stake , an operation can be considered final with quasi - certainty if there are at least 5 blocks built on top of it . See Emmy * TZIP for more detailed explanations . than 33% of stake, an operation can be considered final with quasi-certainty if there are at least 5 blocks built on top of it. See Emmy* TZIP for more detailed explanations. *) let num_confirmation_blocks = 5 let get_branch (rpc_config : #Protocol_client_context.full) ~chain ~(block : Block_services.block) branch = let branch = Option.value ~default:0 branch in (match block with | `Head n -> return (`Head (n + branch)) | `Hash (h, n) -> return (`Hash (h, n + branch)) | `Alias (a, n) -> return (`Alias (a, n)) | `Genesis -> return `Genesis | `Level i -> return (`Level i)) >>=? fun block -> Shell_services.Blocks.hash rpc_config ~chain ~block () >>=? fun hash -> Shell_services.Chain.chain_id rpc_config ~chain () >>=? fun chain_id -> return (chain_id, hash) type 'kind preapply_result = Operation_hash.t * 'kind operation * 'kind operation_metadata type 'kind result_list = Operation_hash.t * 'kind contents_list * 'kind contents_result_list type 'kind result = Operation_hash.t * 'kind contents * 'kind contents_result let get_manager_operation_gas_and_fee contents = let open Operation in let l = to_list (Contents_list contents) in List.fold_left (fun acc -> function | Contents (Manager_operation {fee; gas_limit; _}) -> ( match acc with | Error _ as e -> e | Ok (total_fee, total_gas) -> ( match Tez.(total_fee +? fee) with | Ok total_fee -> Ok (total_fee, Gas.Arith.add total_gas gas_limit) | Error _ as e -> e)) | _ -> acc) (Ok (Tez.zero, Gas.Arith.zero)) l type fee_parameter = { minimal_fees : Tez.t; minimal_nanotez_per_byte : Q.t; minimal_nanotez_per_gas_unit : Q.t; force_low_fee : bool; fee_cap : Tez.t; burn_cap : Tez.t; } let dummy_fee_parameter = { minimal_fees = Tez.zero; minimal_nanotez_per_byte = Q.zero; minimal_nanotez_per_gas_unit = Q.zero; force_low_fee = false; fee_cap = Tez.one; burn_cap = Tez.zero; } let z_mutez_of_q_nanotez (ntz : Q.t) = let q_mutez = Q.div ntz (Q.of_int 1000) in Z.cdiv q_mutez.Q.num q_mutez.Q.den let check_fees : type t. #Protocol_client_context.full -> fee_parameter -> t contents_list -> int -> unit Lwt.t = fun cctxt config op size -> match get_manager_operation_gas_and_fee op with FIXME | Ok (fee, gas) -> if Tez.compare fee config.fee_cap > 0 then cctxt#error "The proposed fee (%s%a) are higher than the configured fee cap \ (%s%a).@\n\ \ Use `--fee-cap %a` to emit this operation anyway." Client_proto_args.tez_sym Tez.pp fee Client_proto_args.tez_sym Tez.pp config.fee_cap Tez.pp fee >>= fun () -> exit 1 else let fees_in_nanotez = Q.mul (Q.of_int64 (Tez.to_mutez fee)) (Q.of_int 1000) in let minimal_fees_in_nanotez = Q.mul (Q.of_int64 (Tez.to_mutez config.minimal_fees)) (Q.of_int 1000) in let minimal_fees_for_gas_in_nanotez = Q.mul config.minimal_nanotez_per_gas_unit (Q.of_bigint (Gas.Arith.integral_to_z gas)) in let minimal_fees_for_size_in_nanotez = Q.mul config.minimal_nanotez_per_byte (Q.of_int size) in let estimated_fees_in_nanotez = Q.add minimal_fees_in_nanotez (Q.add minimal_fees_for_gas_in_nanotez minimal_fees_for_size_in_nanotez) in let estimated_fees_in_mutez = z_mutez_of_q_nanotez estimated_fees_in_nanotez in let estimated_fees = match Tez.of_mutez (Z.to_int64 estimated_fees_in_mutez) with | None -> assert false | Some fee -> fee in if (not config.force_low_fee) && Q.compare fees_in_nanotez estimated_fees_in_nanotez < 0 then cctxt#error "The proposed fee (%s%a) are lower than the fee that baker expect \ by default (%s%a).@\n\ \ Use `--force-low-fee` to emit this operation anyway." Client_proto_args.tez_sym Tez.pp fee Client_proto_args.tez_sym Tez.pp estimated_fees >>= fun () -> exit 1 else Lwt.return_unit let print_for_verbose_signing ppf ~watermark ~bytes ~branch ~contents = let open Format in pp_open_vbox ppf 0 ; let item f = pp_open_hovbox ppf 4 ; pp_print_string ppf " * " ; f ppf () ; pp_close_box ppf () ; pp_print_cut ppf () in let hash_pp l = fprintf ppf "%s" (Base58.raw_encode Blake2B.(hash_bytes l |> to_string)) in item (fun ppf () -> pp_print_text ppf "Branch: " ; Block_hash.pp ppf branch) ; item (fun ppf () -> fprintf ppf "Watermark: `%a` (0x%s)" Signature.pp_watermark watermark (Hex.of_bytes (Signature.bytes_of_watermark watermark) |> Hex.show)) ; item (fun ppf () -> pp_print_text ppf "Operation bytes: " ; (fun n c -> pp_print_char ppf c ; if n < 72 then n + 1 else ( pp_print_space ppf () ; 0)) 0 (Hex.of_bytes bytes |> Hex.show) |> ignore) ; item (fun ppf () -> pp_print_text ppf "Blake 2B Hash (raw): " ; hash_pp [bytes]) ; item (fun ppf () -> pp_print_text ppf "Blake 2B Hash (ledger-style, with operation watermark): " ; hash_pp [Signature.bytes_of_watermark watermark; bytes]) ; let json = Data_encoding.Json.construct Operation.unsigned_encoding ({branch}, Contents_list contents) in item (fun ppf () -> pp_print_text ppf "JSON encoding: " ; Data_encoding.Json.pp ppf json) ; pp_close_box ppf () let preapply (type t) (cctxt : #Protocol_client_context.full) ~chain ~block ?(verbose_signing = false) ?fee_parameter ?branch ?src_sk (contents : t contents_list) = get_branch cctxt ~chain ~block branch >>=? fun (chain_id, branch) -> let bytes = Data_encoding.Binary.to_bytes_exn Operation.unsigned_encoding ({branch}, Contents_list contents) in (match src_sk with | None -> return_none | Some src_sk -> let watermark = match contents with | Single (Endorsement _) -> Signature.(Endorsement chain_id) | _ -> Signature.Generic_operation in (if verbose_signing then cctxt#message "Pre-signature information (verbose signing):@.%t%!" (print_for_verbose_signing ~watermark ~bytes ~branch ~contents) else Lwt.return_unit) >>= fun () -> Client_keys.sign cctxt ~watermark src_sk bytes >>=? fun signature -> return_some signature) >>=? fun signature -> let op : _ Operation.t = {shell = {branch}; protocol_data = {contents; signature}} in let oph = Operation.hash op in let size = Bytes.length bytes + Signature.size in (match fee_parameter with | Some fee_parameter -> check_fees cctxt fee_parameter contents size | None -> Lwt.return_unit) >>= fun () -> Protocol_client_context.Alpha_block_services.Helpers.Preapply.operations cctxt ~chain ~block [Operation.pack op] >>=? function | [(Operation_data op', Operation_metadata result)] -> ( match ( Operation.equal op {shell = {branch}; protocol_data = op'}, Apply_results.kind_equal_list contents result.contents ) with | (Some Operation.Eq, Some Apply_results.Eq) -> return ((oph, op, result) : t preapply_result) | _ -> failwith "Unexpected result") | _ -> failwith "Unexpected result" let simulate (type t) (cctxt : #Protocol_client_context.full) ~chain ~block ?branch ?(latency = Plugin.default_operation_inclusion_latency) (contents : t contents_list) = get_branch cctxt ~chain ~block branch >>=? fun (_chain_id, branch) -> let op : _ Operation.t = {shell = {branch}; protocol_data = {contents; signature = None}} in let oph = Operation.hash op in Chain_services.chain_id cctxt ~chain () >>=? fun chain_id -> Plugin.RPC.Scripts.simulate_operation cctxt (chain, block) ~op:(Operation.pack op) ~chain_id ~latency >>=? function | (Operation_data op', Operation_metadata result) -> ( match ( Operation.equal op {shell = {branch}; protocol_data = op'}, Apply_results.kind_equal_list contents result.contents ) with | (Some Operation.Eq, Some Apply_results.Eq) -> return ((oph, op, result) : t preapply_result) | _ -> failwith "Unexpected result") | _ -> failwith "Unexpected result" let estimated_gas_single (type kind) (Manager_operation_result {operation_result; internal_operation_results; _} : kind Kind.manager contents_result) = let consumed_gas (type kind) (result : kind manager_operation_result) = match result with | Applied (Transaction_result {consumed_gas; _}) -> Ok consumed_gas | Applied (Origination_result {consumed_gas; _}) -> Ok consumed_gas | Applied (Reveal_result {consumed_gas}) -> Ok consumed_gas | Applied (Delegation_result {consumed_gas}) -> Ok consumed_gas | Applied (Register_global_constant_result {consumed_gas; _}) -> Ok consumed_gas | Skipped _ -> assert false | Backtracked (_, None) -> | Backtracked (_, Some errs) -> Error (Environment.wrap_tztrace errs) | Failed (_, errs) -> Error (Environment.wrap_tztrace errs) in consumed_gas operation_result >>? fun acc -> List.fold_left_e (fun acc (Internal_operation_result (_, r)) -> consumed_gas r >>? fun gas -> Ok (Gas.Arith.add acc gas)) acc internal_operation_results let estimated_storage_single (type kind) origination_size (Manager_operation_result {operation_result; internal_operation_results; _} : kind Kind.manager contents_result) = let storage_size_diff (type kind) (result : kind manager_operation_result) = match result with | Applied (Transaction_result {paid_storage_size_diff; allocated_destination_contract; _}) -> if allocated_destination_contract then Ok (Z.add paid_storage_size_diff origination_size) else Ok paid_storage_size_diff | Applied (Origination_result {paid_storage_size_diff; _}) -> Ok (Z.add paid_storage_size_diff origination_size) | Applied (Reveal_result _) -> Ok Z.zero | Applied (Delegation_result _) -> Ok Z.zero | Applied (Register_global_constant_result {size_of_constant; _}) -> Ok size_of_constant | Skipped _ -> assert false | Backtracked (_, None) -> | Backtracked (_, Some errs) -> Error (Environment.wrap_tztrace errs) | Failed (_, errs) -> Error (Environment.wrap_tztrace errs) in storage_size_diff operation_result >>? fun acc -> List.fold_left_e (fun acc (Internal_operation_result (_, r)) -> storage_size_diff r >>? fun storage -> Ok (Z.add acc storage)) acc internal_operation_results let estimated_storage origination_size res = let rec estimated_storage : type kind. kind contents_result_list -> _ = function | Single_result (Manager_operation_result _ as res) -> estimated_storage_single origination_size res | Single_result _ -> Ok Z.zero | Cons_result (res, rest) -> estimated_storage_single origination_size res >>? fun storage1 -> estimated_storage rest >>? fun storage2 -> Ok (Z.add storage1 storage2) in estimated_storage res >>? fun diff -> Ok (Z.max Z.zero diff) let originated_contracts_single (type kind) (Manager_operation_result {operation_result; internal_operation_results; _} : kind Kind.manager contents_result) = let originated_contracts (type kind) (result : kind manager_operation_result) = match result with | Applied (Transaction_result {originated_contracts; _}) -> Ok originated_contracts | Applied (Origination_result {originated_contracts; _}) -> Ok originated_contracts | Applied (Register_global_constant_result _) -> Ok [] | Applied (Reveal_result _) -> Ok [] | Applied (Delegation_result _) -> Ok [] | Skipped _ -> assert false | Backtracked (_, None) -> | Backtracked (_, Some errs) -> Error (Environment.wrap_tztrace errs) | Failed (_, errs) -> Error (Environment.wrap_tztrace errs) in originated_contracts operation_result >>? fun acc -> let acc = List.rev acc in List.fold_left_e (fun acc (Internal_operation_result (_, r)) -> originated_contracts r >>? fun contracts -> Ok (List.rev_append contracts acc)) acc internal_operation_results let rec originated_contracts : type kind. kind contents_result_list -> _ = function | Single_result (Manager_operation_result _ as res) -> originated_contracts_single res >|? List.rev | Single_result _ -> Ok [] | Cons_result (res, rest) -> originated_contracts_single res >>? fun contracts1 -> originated_contracts rest >>? fun contracts2 -> Ok (List.rev_append contracts1 contracts2) let originated_contracts ~force results = match originated_contracts results with Error _ when force -> Ok [] | e -> e let detect_script_failure : type kind. kind operation_metadata -> _ = let rec detect_script_failure : type kind. kind contents_result_list -> _ = let detect_script_failure_single (type kind) (Manager_operation_result {operation_result; internal_operation_results; _} : kind Kind.manager contents_result) = let detect_script_failure (type kind) (result : kind manager_operation_result) = match result with | Applied _ -> Ok () | Skipped _ -> assert false | Backtracked (_, None) -> Ok () | Backtracked (_, Some errs) -> record_trace (error_of_fmt "The transfer simulation failed.") (Error (Environment.wrap_tztrace errs)) | Failed (_, errs) -> record_trace (error_of_fmt "The transfer simulation failed.") (Error (Environment.wrap_tztrace errs)) in detect_script_failure operation_result >>? fun () -> List.iter_e (fun (Internal_operation_result (_, r)) -> detect_script_failure r) internal_operation_results in function | Single_result (Manager_operation_result _ as res) -> detect_script_failure_single res | Single_result _ -> Ok () | Cons_result (res, rest) -> detect_script_failure_single res >>? fun () -> detect_script_failure rest in fun {contents} -> detect_script_failure contents let safety_guard = Gas.Arith.(integral_of_int_exn 100) { 2 High - level description of the automatic gas patching algorithm } When the user wants to inject a list of operations , some of which might have unspecified gas , fees or storage limit , the client performs a { e simulation } to estimate those limits and assign sensible values to them . The simulation works as follows : 1 . limits are assigned to dummy , high values to ensure that the operations can be simulated - 1.a ) when a list of operations is partially specified , the algorithm allocates to each unspecified operation an equal portion of the maximum gas per block minus the gas consumed by the operations that do specify their limit 2 . the algorithm retrieves the effectively consumed gas and storage from the receipt 3 . the algorithm assigns slight overapproximations to the operation 4 . a default fee is computed and set {2 High-level description of the automatic gas patching algorithm} When the user wants to inject a list of operations, some of which might have unspecified gas, fees or storage limit, the client performs a {e simulation} to estimate those limits and assign sensible values to them. The simulation works as follows: 1. limits are assigned to dummy, high values to ensure that the operations can be simulated - 1.a) when a list of operations is partially specified, the algorithm allocates to each unspecified operation an equal portion of the maximum gas per block minus the gas consumed by the operations that do specify their limit 2. the algorithm retrieves the effectively consumed gas and storage from the receipt 3. the algorithm assigns slight overapproximations to the operation 4. a default fee is computed and set *) let may_patch_limits (type kind) (cctxt : #Protocol_client_context.full) ~fee_parameter ~chain ~block ?branch (annotated_contents : kind Annotated_manager_operation.annotated_list) : kind Kind.manager contents_list tzresult Lwt.t = Tezos_client_base.Client_confirmations.wait_for_bootstrapped cctxt >>=? fun () -> Alpha_services.Constants.all cctxt (chain, block) >>=? fun { parametric = { hard_gas_limit_per_operation; hard_gas_limit_per_block; hard_storage_limit_per_operation; origination_size; cost_per_byte; _; }; _; } -> let user_gas_limit_needs_patching user_gas_limit = Limit.fold user_gas_limit ~unknown:true ~known:(fun user_gas_limit -> Gas.Arith.( user_gas_limit < zero || hard_gas_limit_per_operation < user_gas_limit)) in let user_storage_limit_needs_patching user_storage_limit = Limit.fold user_storage_limit ~unknown:true ~known:(fun user_storage_limit -> Z.Compare.( user_storage_limit < Z.zero || hard_storage_limit_per_operation < user_storage_limit)) in let gas_patching_stats (Annotated_manager_operation.Manager_info c) need_patching gas_consumed = if user_gas_limit_needs_patching c.gas_limit then (need_patching + 1, gas_consumed) else ( need_patching, Gas.Arith.add gas_consumed (Limit.value ~when_unknown:Gas.Arith.zero c.gas_limit) ) in let rec gas_patching_stats_list : type kind. kind Annotated_manager_operation.annotated_list -> int -> Saturation_repr.may_saturate Saturation_repr.t -> int * Saturation_repr.may_saturate Saturation_repr.t = fun op need_patching gas_consumed -> match op with | Single_manager minfo -> gas_patching_stats minfo need_patching gas_consumed | Cons_manager (minfo, rest) -> let (need_patching, gas_consumed) = gas_patching_stats minfo need_patching gas_consumed in gas_patching_stats_list rest need_patching gas_consumed in let may_need_patching_single : type kind. Gas.Arith.integral -> kind Annotated_manager_operation.t -> kind Annotated_manager_operation.t option = fun gas_limit_per_patched_op op -> match op with | Manager_info c -> let needs_patching = Limit.is_unknown c.fee || user_gas_limit_needs_patching c.gas_limit || user_storage_limit_needs_patching c.storage_limit in if not needs_patching then None else let gas_limit = if user_gas_limit_needs_patching c.gas_limit then Limit.known gas_limit_per_patched_op else c.gas_limit in let storage_limit = if user_storage_limit_needs_patching c.storage_limit then Limit.known hard_storage_limit_per_operation else c.storage_limit in let fee = Limit.value ~when_unknown:Tez.zero c.fee in Some (Manager_info {c with gas_limit; storage_limit; fee = Limit.known fee}) in let may_need_patching gas_limit_per_patched_op ops = let rec loop : type kind. kind Annotated_manager_operation.annotated_list -> kind Annotated_manager_operation.annotated_list option = function | Single_manager annotated_op -> Option.map (fun op -> Annotated_manager_operation.Single_manager op) @@ may_need_patching_single gas_limit_per_patched_op annotated_op | Cons_manager (annotated_op, rest) -> ( let annotated_op_opt = may_need_patching_single gas_limit_per_patched_op annotated_op in let rest_opt = loop rest in match (annotated_op_opt, rest_opt) with | (None, None) -> None | _ -> let op = Option.value ~default:annotated_op annotated_op_opt in let rest = Option.value ~default:rest rest_opt in Some (Cons_manager (op, rest))) in loop ops in let rec patch_fee : type kind. first:bool -> kind contents -> kind contents = fun ~first -> function | Manager_operation c as op -> ( let size = if first then (WithExceptions.Option.get ~loc:__LOC__ @@ Data_encoding.Binary.fixed_length Tezos_base.Operation.shell_header_encoding) + Data_encoding.Binary.length Operation.contents_encoding (Contents op) + Signature.size else Data_encoding.Binary.length Operation.contents_encoding (Contents op) in let minimal_fees_in_nanotez = Q.mul (Q.of_int64 (Tez.to_mutez fee_parameter.minimal_fees)) (Q.of_int 1000) in let minimal_fees_for_gas_in_nanotez = Q.mul fee_parameter.minimal_nanotez_per_gas_unit (Q.of_bigint @@ Gas.Arith.integral_to_z c.gas_limit) in let minimal_fees_for_size_in_nanotez = Q.mul fee_parameter.minimal_nanotez_per_byte (Q.of_int size) in let fees_in_nanotez = Q.add minimal_fees_in_nanotez @@ Q.add minimal_fees_for_gas_in_nanotez minimal_fees_for_size_in_nanotez in let fees_in_mutez = z_mutez_of_q_nanotez fees_in_nanotez in match Tez.of_mutez (Z.to_int64 fees_in_mutez) with | None -> assert false | Some fee -> if Tez.(fee <= c.fee) then op else patch_fee ~first (Manager_operation {c with fee})) | c -> c in let patch : type kind. first:bool -> kind Annotated_manager_operation.t * kind Kind.manager contents_result -> kind Kind.manager contents tzresult Lwt.t = fun ~first -> function | ((Manager_info c as op), (Manager_operation_result _ as result)) -> (if user_gas_limit_needs_patching c.gas_limit then Lwt.return (estimated_gas_single result) >>=? fun gas -> if Gas.Arith.(gas = zero) then cctxt#message "Estimated gas: none" >>= fun () -> return (Annotated_manager_operation.set_gas_limit (Limit.known Gas.Arith.zero) op) else cctxt#message "Estimated gas: %a units (will add 100 for safety)" Gas.Arith.pp gas >>= fun () -> let safe_gas = Gas.Arith.(add (ceil gas) safety_guard) in let patched_gas = Gas.Arith.min safe_gas hard_gas_limit_per_operation in return (Annotated_manager_operation.set_gas_limit (Limit.known patched_gas) op) else return op) >>=? fun op -> (if user_storage_limit_needs_patching c.storage_limit then Lwt.return (estimated_storage_single (Z.of_int origination_size) result) >>=? fun storage -> if Z.equal storage Z.zero then cctxt#message "Estimated storage: no bytes added" >>= fun () -> return (Annotated_manager_operation.set_storage_limit (Limit.known Z.zero) op) else cctxt#message "Estimated storage: %s bytes added (will add 20 for safety)" (Z.to_string storage) >>= fun () -> let storage_limit = Z.min (Z.add storage (Z.of_int 20)) hard_storage_limit_per_operation in return (Annotated_manager_operation.set_storage_limit (Limit.known storage_limit) op) else return op) >>=? fun op -> if Limit.is_unknown c.fee then let op = Annotated_manager_operation.set_fee (Limit.known Tez.zero) op in Annotated_manager_operation.manager_from_annotated op >>?= fun cm -> return (patch_fee ~first cm) else Lwt.return (Annotated_manager_operation.manager_from_annotated op) in let rec patch_list : type kind. bool -> kind Annotated_manager_operation.annotated_list -> kind Kind.manager contents_result_list -> kind Kind.manager contents_list tzresult Lwt.t = fun first annotated_list result_list -> match (annotated_list, result_list) with | (Single_manager annotated, Single_result res) -> patch ~first (annotated, res) >>=? fun op -> return (Single op) | (Cons_manager (annotated, annotated_rest), Cons_result (res, res_rest)) -> patch ~first (annotated, res) >>=? fun op -> patch_list false annotated_rest res_rest >>=? fun rest -> return (Cons (op, rest)) | _ -> assert false in let gas_limit_per_patched_op = let (need_gas_patching, gas_consumed) = gas_patching_stats_list annotated_contents 0 Gas.Arith.zero in if need_gas_patching = 0 then hard_gas_limit_per_operation else let remaining_gas = Gas.Arith.sub hard_gas_limit_per_block gas_consumed in let average_per_operation_gas = Gas.Arith.integral_exn @@ Z.div (Gas.Arith.integral_to_z remaining_gas) (Z.of_int need_gas_patching) in Gas.Arith.min hard_gas_limit_per_operation average_per_operation_gas in match may_need_patching gas_limit_per_patched_op annotated_contents with | Some annotated_for_simulation -> Lwt.return (Annotated_manager_operation.manager_list_from_annotated annotated_for_simulation) >>=? fun contents_for_simulation -> simulate cctxt ~chain ~block ?branch contents_for_simulation >>=? fun (_, _, result) -> (match detect_script_failure result with | Ok () -> return_unit | Error _ -> cctxt#message "@[<v 2>This simulation failed:@,%a@]" Operation_result.pp_operation_result (contents_for_simulation, result.contents) >>= fun () -> return_unit) >>=? fun () -> ( Lwt.return (estimated_storage (Z.of_int origination_size) result.contents) >>=? fun storage -> Lwt.return (Environment.wrap_tzresult Tez.(cost_per_byte *? Z.to_int64 storage)) >>=? fun burn -> if Tez.(burn > fee_parameter.burn_cap) then cctxt#error "The operation will burn %s%a which is higher than the configured \ burn cap (%s%a).@\n\ \ Use `--burn-cap %a` to emit this operation." Client_proto_args.tez_sym Tez.pp burn Client_proto_args.tez_sym Tez.pp fee_parameter.burn_cap Tez.pp burn >>= fun () -> exit 1 else return_unit ) >>=? fun () -> patch_list true annotated_contents result.contents | None -> Lwt.return (Annotated_manager_operation.manager_list_from_annotated annotated_contents) let inject_operation_internal (type kind) cctxt ~chain ~block ?confirmations ?(dry_run = false) ?(simulation = false) ?(force = false) ?branch ?src_sk ?verbose_signing ~fee_parameter (contents : kind contents_list) = (if simulation then simulate cctxt ~chain ~block ?branch contents else preapply cctxt ~chain ~block ~fee_parameter ?verbose_signing ?branch ?src_sk contents) >>=? fun (_oph, op, result) -> (match detect_script_failure result with | Ok () -> return_unit | Error _ as res -> cctxt#message "@[<v 2>This simulation failed:@,%a@]" Operation_result.pp_operation_result (op.protocol_data.contents, result.contents) >>= fun () -> if force then return_unit else Lwt.return res) >>=? fun () -> let bytes = Data_encoding.Binary.to_bytes_exn Operation.encoding (Operation.pack op) in if dry_run || simulation then let oph = Operation_hash.hash_bytes [bytes] in cctxt#message "@[<v 0>Operation: 0x%a@,Operation hash is '%a'@]" Hex.pp (Hex.of_bytes bytes) Operation_hash.pp oph >>= fun () -> cctxt#message "@[<v 2>Simulation result:@,%a@]" Operation_result.pp_operation_result (op.protocol_data.contents, result.contents) >>= fun () -> return (oph, op.protocol_data.contents, result.contents) else Shell_services.Injection.operation cctxt ~chain bytes >>=? fun oph -> cctxt#message "Operation successfully injected in the node." >>= fun () -> cctxt#message "Operation hash is '%a'" Operation_hash.pp oph >>= fun () -> (match confirmations with | None -> cctxt#message "@[<v 0>NOT waiting for the operation to be included.@,\ Use command@,\ \ tezos-client wait for %a to be included --confirmations %d \ --branch %a@,\ and/or an external block explorer to make sure that it has been \ included.@]" Operation_hash.pp oph num_confirmation_blocks Block_hash.pp op.shell.branch >>= fun () -> return result | Some confirmations -> ( cctxt#message "Waiting for the operation to be included..." >>= fun () -> Client_confirmations.wait_for_operation_inclusion ~branch:op.shell.branch ~confirmations cctxt ~chain oph >>=? fun (h, i, j) -> Alpha_block_services.Operations.operation cctxt ~chain ~block:(`Hash (h, 0)) i j >>=? fun op' -> match op'.receipt with | None -> failwith "Internal error: pruned metadata." | Some No_operation_metadata -> failwith "Internal error: unexpected receipt." | Some (Operation_metadata receipt) -> ( match Apply_results.kind_equal_list contents receipt.contents with | Some Apply_results.Eq -> return (receipt : kind operation_metadata) | None -> failwith "Internal error: unexpected receipt."))) >>=? fun result -> cctxt#message "@[<v 2>This sequence of operations was run:@,%a@]" Operation_result.pp_operation_result (op.protocol_data.contents, result.contents) >>= fun () -> Lwt.return (originated_contracts result.contents ~force) >>=? fun contracts -> List.iter_s (fun c -> cctxt#message "New contract %a originated." Contract.pp c) contracts >>= fun () -> (match confirmations with | None -> Lwt.return_unit | Some number -> if number >= num_confirmation_blocks then cctxt#message "The operation was included in a block %d blocks ago." number else cctxt#message "@[<v 0>The operation has only been included %d blocks ago.@,\ We recommend to wait more.@,\ Use command@,\ \ tezos-client wait for %a to be included --confirmations %d \ --branch %a@,\ and/or an external block explorer.@]" number Operation_hash.pp oph num_confirmation_blocks Block_hash.pp op.shell.branch) >>= fun () -> return (oph, op.protocol_data.contents, result.contents) let inject_operation (type kind) cctxt ~chain ~block ?confirmations ?(dry_run = false) ?(simulation = false) ?branch ?src_sk ?verbose_signing ~fee_parameter (contents : kind contents_list) = Tezos_client_base.Client_confirmations.wait_for_bootstrapped cctxt >>=? fun () -> inject_operation_internal cctxt ~chain ~block ?confirmations ~dry_run ~simulation ?branch ?src_sk ?verbose_signing ~fee_parameter (contents : kind contents_list) let prepare_manager_operation ~fee ~gas_limit ~storage_limit operation = Annotated_manager_operation.Manager_info {source = None; fee; gas_limit; storage_limit; counter = None; operation} let cost_of_manager_operation = Gas.Arith.integral_of_int_exn 1_000 let reveal_error_message = "Requested operation requires to perform a public key revelation beforehand.\n\ This cannot be done automatically when a custom fee or storage limit is \ given.\n\ If you wish to use a custom fee or storage limit, please first perform the \ reveal operation separately using the dedicated command.\n\ Otherwise, please do not specify custom fee or storage parameters." let reveal_error (cctxt : #Protocol_client_context.full) = cctxt#error "%s" reveal_error_message let inject_manager_operation cctxt ~chain ~block ?branch ?confirmations ?dry_run ?verbose_signing ?simulation ?force ~source ~src_pk ~src_sk ~fee ~gas_limit ~storage_limit ?counter ~fee_parameter (type kind) (operations : kind Annotated_manager_operation.annotated_list) : (Operation_hash.t * kind Kind.manager contents_list * kind Kind.manager contents_result_list) tzresult Lwt.t = (match counter with | None -> Alpha_services.Contract.counter cctxt (chain, block) source >>=? fun pcounter -> let counter = Z.succ pcounter in return counter | Some counter -> return counter) >>=? fun counter -> Alpha_services.Contract.manager_key cctxt (chain, block) source >>=? fun key -> [ has_reveal ] assumes that a Reveal operation only appears as the first of a batch let has_reveal : type kind. kind Annotated_manager_operation.annotated_list -> bool = function | Single_manager (Manager_info {operation = Reveal _; _}) -> true | Cons_manager (Manager_info {operation = Reveal _; _}, _) -> true | _ -> false in let apply_specified_options counter op = Annotated_manager_operation.set_source source op >>? fun op -> Annotated_manager_operation.set_counter counter op >>? fun op -> Annotated_manager_operation.join_fee fee op >>? fun op -> Annotated_manager_operation.join_gas_limit gas_limit op >>? fun op -> Annotated_manager_operation.join_storage_limit storage_limit op in let rec build_contents : type kind. Z.t -> kind Annotated_manager_operation.annotated_list -> kind Annotated_manager_operation.annotated_list tzresult = fun counter -> function | Single_manager op -> apply_specified_options counter op >|? fun op -> Annotated_manager_operation.Single_manager op | Cons_manager (op, rest) -> apply_specified_options counter op >>? fun op -> build_contents (Z.succ counter) rest >|? fun rest -> Annotated_manager_operation.Cons_manager (op, rest) in match key with | None when not (has_reveal operations) -> ( (if not (Limit.is_unknown fee && Limit.is_unknown storage_limit) then reveal_error cctxt else return_unit) >>=? fun () -> let reveal = prepare_manager_operation ~fee:Limit.unknown ~gas_limit:(Limit.known cost_of_manager_operation) ~storage_limit:Limit.unknown (Reveal src_pk) in Annotated_manager_operation.set_source source reveal >>?= fun reveal -> Annotated_manager_operation.set_counter counter reveal >>?= fun reveal -> build_contents (Z.succ counter) operations >>?= fun rest -> let contents = Annotated_manager_operation.Cons_manager (reveal, rest) in may_patch_limits cctxt ~fee_parameter ~chain ~block ?branch contents >>=? fun contents -> inject_operation_internal cctxt ~chain ~block ?confirmations ?dry_run ?simulation ?force ~fee_parameter ?verbose_signing ?branch ~src_sk contents >>=? fun (oph, op, result) -> match pack_contents_list op result with | Cons_and_result (_, _, rest) -> let (op, result) = unpack_contents_list rest in return (oph, op, result) | _ -> assert false) | Some _ when has_reveal operations -> failwith "The manager key was previously revealed." | _ -> build_contents counter operations >>?= fun contents -> may_patch_limits cctxt ~fee_parameter ~chain ~block ?branch contents >>=? fun contents -> inject_operation_internal cctxt ~chain ~block ?confirmations ?dry_run ?verbose_signing ?simulation ?force ~fee_parameter ?branch ~src_sk contents
1637fab8566ecf5319561cbf2d92fceb96a44572d7c10d8afb17cd5eee714e87
webyrd/cool-relational-interpreter-examples
variadic-lambda-tests.scm
;; The version of the relational interpreter in ;; 'interp-with-variadic-lambda.scm' supports 'apply', variadic ;; 'lambda'/application, multi-argument 'lambda'/application, and a ;; fair number of built-ins, such as 'quote', 'list', and 'cons'. ;; ;; Importantly, 'apply' has been moved towards the top of the 'conde' ;; in 'eval-expo', ensuring that the answers will contain many uses of ;; 'apply'. In general, to get more answers containing a form or ;; primitive function, move the form towards the top of the 'conde' in ;; 'eval-expo' (and vice versa to de-emphasize a form). The ordering ;; of the 'conde' clauses give us some crude control over how ;; miniKanren explores the search space of terms. (load "interp-with-variadic-lambda.scm") (load "../mk/test-check.scm") (load "../mk/matche.scm") ;; Helper Scheme predicate for testing (define member? (lambda (x ls) (not (not (member x ls))))) ;; Standard Scheme definition of append. I've wrapped the definition ;; in a 'let' to avoid shadowing Scheme's built-in 'append' ;; definition. (let () (define append (lambda (l s) (cond ((null? l) s) (else (cons (car l) (append (cdr l) s)))))) (test "Scheme append-1" (append '(a b c) '(d e)) '(a b c d e)) ) Our normal relational ' appendo ' definition , written in miniKanren . ;; 'appendo' doesn't look very Scheme-like, unfortunately. (let () (define appendo (lambda (l s out) (conde ((== '() l) (== s out)) ((fresh (a d res) (== `(,a . ,d) l) (== `(,a . ,res) out) (appendo d s res)))))) (test "appendo-1" (run* (q) (appendo '(a b c) '(d e) q)) '((a b c d e))) (test "appendo-2" (run* (q) (appendo '(a b c) q '(a b c d e))) '((d e))) (test "appendo-3" (run* (x y) (appendo x y '(a b c d e))) '((() (a b c d e)) ((a) (b c d e)) ((a b) (c d e)) ((a b c) (d e)) ((a b c d) (e)) ((a b c d e) ()))) (test "appendo-4" (run 5 (x y z) (appendo x y z)) '((() _.0 _.0) ((_.0) _.1 (_.0 . _.1)) ((_.0 _.1) _.2 (_.0 _.1 . _.2)) ((_.0 _.1 _.2) _.3 (_.0 _.1 _.2 . _.3)) ((_.0 _.1 _.2 _.3) _.4 (_.0 _.1 _.2 _.3 . _.4)))) ) ;; Even the pattern-matching version of 'appendo' doesn't look that ;; much like the Scheme code. (let () (define appendo (lambda (l s out) (matche (l s out) ((() ,s ,s)) (((,a . ,d) ,s (,a . ,res)) (appendo d s res))))) (test "appendo-1" (run* (q) (appendo '(a b c) '(d e) q)) '((a b c d e))) (test "appendo-2" (run* (q) (appendo '(a b c) q '(a b c d e))) '((d e))) (test "appendo-3" (run* (x y) (appendo x y '(a b c d e))) '((() (a b c d e)) ((a) (b c d e)) ((a b) (c d e)) ((a b c) (d e)) ((a b c d) (e)) ((a b c d e) ()))) (test "appendo-4" (run 5 (x y z) (appendo x y z)) '((() _.0 _.0) ((_.0) _.1 (_.0 . _.1)) ((_.0 _.1) _.2 (_.0 _.1 . _.2)) ((_.0 _.1 _.2) _.3 (_.0 _.1 _.2 . _.3)) ((_.0 _.1 _.2 _.3) _.4 (_.0 _.1 _.2 _.3 . _.4)))) ) ;; With the relational Scheme interpreter written in miniKanren, we ;; can write the *Scheme* definition of 'append', and treat that ;; *function* as a *relation*. This is because the interpreter itself ;; is a relation. ;; ;; Running append "forwards": (test "Scheme-append-under-relational-interpreter-1" (run* (q) (evalo '(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (append '(a b c) '(d e))) q)) '((a b c d e))) ;; Running append "backwards:" (test "Scheme-append-under-relational-interpreter-2" (run 6 (x y) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (append ,x ,y)) '(a b c d e))) '(('() '(a b c d e)) ('(a) '(b c d e)) ('(a b) '(c d e)) ('(a b c) '(d e)) ('(a b c d) '(e)) ('(a b c d e) '()))) Replacing ' run 6 ' with ' run * ' in ;; Scheme-append-under-relational-interpreter-2 results in divergence ;; (looping forever). This seems bad. Aren't there only 6 answers? Let 's try to generate a seventh answer : (test "Scheme-append-under-relational-interpreter-3" (run 7 (x y) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (append ,x ,y)) '(a b c d e))) '(('() '(a b c d e)) ('(a) '(b c d e)) ('(a b) '(c d e)) ('(a b c) '(d e)) ('(a b c d) '(e)) ('(a b c d e) '()) ('(a b c d e) (list)))) ;; Whoa! The last answer has a call to 'list' with no arguments, ;; producing the empty list! Because we are running 'append' in the ;; context of the relational Scheme interpreter, the logic variables ;; 'x' and 'y' in the body of the 'letrec' represent *arbitrary Scheme ;; expressions* that evaluate to lists of symbols. ;; Let's look at a few more answers: (test "Scheme-append-under-relational-interpreter-4" (run 20 (x y) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (append ,x ,y)) '(a b c d e))) '(('() '(a b c d e)) ('(a) '(b c d e)) ('(a b) '(c d e)) ('(a b c) '(d e)) ('(a b c d) '(e)) ('(a b c d e) '()) ('(a b c d e) (list)) (('() (apply (lambda _.0 '(a b c d e)) '())) (=/= ((_.0 quote))) (sym _.0)) (('(a b c d e) (apply (lambda _.0 _.0) '())) (sym _.0)) (('(a) (apply (lambda _.0 '(b c d e)) '())) (=/= ((_.0 quote))) (sym _.0)) (('(a b) (apply (lambda _.0 '(c d e)) '())) (=/= ((_.0 quote))) (sym _.0)) (('(a b c) (apply (lambda _.0 '(d e)) '())) (=/= ((_.0 quote))) (sym _.0)) (('(a b c d) (apply (lambda _.0 '(e)) '())) (=/= ((_.0 quote))) (sym _.0)) (('(a b c d e) (apply (lambda _.0 '()) '())) (=/= ((_.0 quote))) (sym _.0)) ('(a b c d) (list 'e)) (('(a b c d) (apply (lambda _.0 _.0) '(e))) (sym _.0)) (('() (apply (lambda _.0 '(a b c d e)) '(_.1))) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))) (('(a) (apply (lambda _.0 '(b c d e)) '(_.1))) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))) (('(a b) (apply (lambda _.0 '(c d e)) '(_.1))) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))) (('(a b c) (apply (lambda _.0 '(d e)) '(_.1))) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))))) ;; Sure enough, later answers call 'list', and even use variadic ;; 'lambda' and procedure application. So our Scheme 'append', ;; running in the relational interpreter, is more general than ;; 'appendo'! ;; We can recapture the behavior of 'appendo', in which we restrict ;; the arguments to lists of values (rather than expressions that ;; *evaluate* to lists of values) by a careful use of 'quote' inside ;; the body of the 'letrec': (test "Scheme-append-under-relational-interpreter-5" (run* (x y) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (append (quote ,x) (quote ,y))) '(a b c d e))) '((() (a b c d e)) ((a) (b c d e)) ((a b) (c d e)) ((a b c) (d e)) ((a b c d) (e)) ((a b c d e) ()))) In addition to inferring the two list arguments in an ' append ' ;; call, we can infer the actual use of 'append' in the call! Our first attempt to infer the use of ' append ' is unsuccessful . ;; miniKanren "cheats" by generating a variadic lambda expression ;; whose body returns the "output" list. (test "infer-append-use-1" (run 1 (q) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (,q '(a b c) '(d e))) '(a b c d e))) '(((lambda _.0 '(a b c d e)) (=/= ((_.0 quote))) (sym _.0)))) ;; We can use the 'absento' constraint to keep miniKanren from cheating . The constraint ' ( absento ' a q ) ' ensures that the symbol ' a'---which occurs in both the input to the call and the ;; does not occur in the expression we are trying to infer. ;; This results in the expected answer , ' append ' , and a second ;; expression that also evaluates to the append procedure. (test "infer-append-use-2" (run 2 (q) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (,q '(a b c) '(d e))) '(a b c d e)) (absento 'a q)) '(append ((apply (lambda _.0 append) '()) (=/= ((_.0 a)) ((_.0 append))) (sym _.0)))) ;; We can also infer missing sub-expressions from the definition of ;; 'append'. Here we infer the missing '(car l)' call from the 'else' branch of the ' if ' expression . The second answer is an expression ;; whose behavior is equivalent to that of '(car l)'. ;; ;; Several subexpressions are quick to infer. Other subexpressions ;; take a very long time to infer. The interpreter cannot (yet) be ;; practically used for example-based program synthesis of programs ;; like 'append', but there may be improvements to the miniKanren ;; implementation, the relational interpreter, and our inference ;; techniques which would make example-based synthesis feasible in ;; practice. We are currently exploring this research area. (test "infer-car-1" (run 2 (q) (absento 'a q) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons ,q (append (cdr l) s)))))) (append '(a b c) '(d e))) '(a b c d e))) '((car l) ((apply (lambda _.0 (car l)) s) (=/= ((_.0 a)) ((_.0 car)) ((_.0 l))) (sym _.0)))) One fun thing we can do with the relational interpreter is generate ;; Scheme programs that evaluate to a given value. For example, here are ten Scheme expressions that evaluate to the list ' ( I love you ) ' . (test "I-love-you-1" (run 10 (q) (evalo q '(I love you))) '('(I love you) ((apply (lambda _.0 '(I love you)) '()) (=/= ((_.0 quote))) (sym _.0)) ((apply (lambda _.0 '(I love you)) '(_.1)) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))) ((apply (lambda _.0 '(I love you)) '(_.1 _.2)) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1) (closure _.2))) ((apply (lambda (_.0) '(I love you)) '(_.1)) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))) ((apply (lambda (_.0) _.0) '((I love you))) (sym _.0)) (list 'I 'love 'you) (((lambda _.0 '(I love you))) (=/= ((_.0 quote))) (sym _.0)) ((apply (lambda _.0 '(I love you)) '(_.1 _.2 _.3)) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1) (closure _.2) (closure _.3))) (((lambda _.0 '(I love you)) '_.1) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))))) ;; Here is where the real fun begins! ;; We can run a similar query to the one above , generating one ;; thousand Scheme expressions that evaluate to the list '(I love you)'. ;; However, we introduce a new twist. We place the query variable ;; in the body of the 'letrec' in which we have defined 'append'. Therefore , miniKanren is free to infer expressions that use ' append ' , ;; even though 'append' is not one of the primitives built into ;; the relational Scheme interpreter! (define I-love-you-append (run 1000 (q) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) ,q) '(I love you)))) ;; Here are a few interesting answers, all of which evaluate to '(I love you)'. (test "I-love-you-append-1" (member? '(apply append '((I love) (you))) I-love-you-append) #t) (test "I-love-you-append-2" (member? '((apply (lambda _.0 (apply append '((I love) (you)))) '()) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 quote))) (sym _.0)) I-love-you-append) #t) (test "I-love-you-append-3" (member? '(((lambda _.0 '(I love you)) append append append append) (=/= ((_.0 quote))) (sym _.0)) I-love-you-append) #t) (test "I-love-you-append-4" (member? '((apply (lambda _.0 (apply append '((I) (love you)))) '()) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 quote))) (sym _.0)) I-love-you-append) #t) (test "I-love-you-append-5" (member? '((apply append (apply (lambda _.0 '((I love) (you))) '())) (=/= ((_.0 quote))) (sym _.0)) I-love-you-append) #t) (test "I-love-you-append-6" (member? '((apply (lambda _.0 (car _.0)) '((I love you))) (=/= ((_.0 car))) (sym _.0)) I-love-you-append) #t) ;; This example illustrates how 'append' can be used as a "dummy" value, ;; passed into the variadic function but never used. (test "I-love-you-append-7" (member? '(((lambda _.0 '(I love you)) append append append append) (=/= ((_.0 quote))) (sym _.0)) I-love-you-append) #t) Our relational interpreter can also generate quines , which are ;; Scheme expressions that evaluate to themselves. (test "simple quines" (run 5 (q) (evalo q q)) '(#t #f ((apply (lambda _.0 (list 'apply (apply (lambda (_.1) _.1) _.0) (list 'quote _.0))) '((lambda _.0 (list 'apply (apply (lambda (_.1) _.1) _.0) (list 'quote _.0))))) (=/= ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (sym _.0 _.1)) ((apply (lambda _.0 (list (apply (lambda _.1 'apply) '()) (apply (lambda (_.2) _.2) _.0) (list 'quote _.0))) '((lambda _.0 (list (apply (lambda _.1 'apply) '()) (apply (lambda (_.2) _.2) _.0) (list 'quote _.0))))) (=/= ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 quote)) ((_.2 closure))) (sym _.0 _.1 _.2)) ((apply (lambda _.0 (list 'apply _.0 (list 'quote _.0))) '(lambda _.0 (list 'apply _.0 (list 'quote _.0)))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)))) ;; And, of course, we can generate quines in the context of the ;; definition of 'append'. (define quines-in-context-of-append (run 60 (q) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) ,q) q))) Here are a few of the generated quines . All but the first and last ;; example use 'append'. (test "quines-in-context-of-append-1" (member? '((apply (lambda _.0 (list 'apply _.0 (list 'quote _.0))) '(lambda _.0 (list 'apply _.0 (list 'quote _.0)))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-2" (member? '((apply (lambda _.0 (list 'apply (apply append _.0) (list 'quote _.0))) '(() (lambda _.0 (list 'apply (apply append _.0) (list 'quote _.0))))) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-3" (member? '((apply (lambda _.0 (list 'apply (apply append _.0) ((lambda _.1 _.1) 'quote _.0))) '(() (lambda _.0 (list 'apply (apply append _.0) ((lambda _.1 _.1) 'quote _.0))))) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (sym _.0 _.1)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-4" (member? '((apply (lambda _.0 (list 'apply (apply append _.0) (apply (lambda _.1 (list 'quote _.1)) _.0))) '(() (lambda _.0 (list 'apply (apply append _.0) (apply (lambda _.1 (list 'quote _.1)) _.0))))) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (sym _.0 _.1)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-5" (member? '((apply (lambda _.0 (list (apply (lambda _.1 'apply) _.0) (apply append _.0) (list 'quote _.0))) '(() (lambda _.0 (list (apply (lambda _.1 'apply) _.0) (apply append _.0) (list 'quote _.0))))) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 quote))) (sym _.0 _.1)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-6" (member? '((apply (lambda _.0 (list 'apply (apply append _.0) (apply (lambda _.1 (list 'quote _.0)) _.0))) '(() (lambda _.0 (list 'apply (apply append _.0) (apply (lambda _.1 (list 'quote _.0)) _.0))))) (=/= ((_.0 _.1)) ((_.0 append)) ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (sym _.0 _.1)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-7" (member? '((apply (lambda _.0 (list 'apply (apply append _.0) (list 'quote (apply (lambda _.1 _.1) _.0)))) '(() (lambda _.0 (list 'apply (apply append _.0) (list 'quote (apply (lambda _.1 _.1) _.0)))))) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (sym _.0 _.1)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-8" (member? '((apply (lambda _.0 (list 'apply (apply (lambda (_.1) _.1) _.0) (apply (lambda _.2 ((lambda _.3 _.3) 'quote _.2)) _.0))) '((lambda _.0 (list 'apply (apply (lambda (_.1) _.1) _.0) (apply (lambda _.2 ((lambda _.3 _.3) 'quote _.2)) _.0))))) (=/= ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.2 closure)) ((_.2 lambda)) ((_.2 quote)) ((_.3 closure))) (sym _.0 _.1 _.2 _.3)) quines-in-context-of-append) #t)
null
https://raw.githubusercontent.com/webyrd/cool-relational-interpreter-examples/c68d261279a301d6dae11ac1e2827a3a619af017/append/variadic-lambda-tests.scm
scheme
The version of the relational interpreter in 'interp-with-variadic-lambda.scm' supports 'apply', variadic 'lambda'/application, multi-argument 'lambda'/application, and a fair number of built-ins, such as 'quote', 'list', and 'cons'. Importantly, 'apply' has been moved towards the top of the 'conde' in 'eval-expo', ensuring that the answers will contain many uses of 'apply'. In general, to get more answers containing a form or primitive function, move the form towards the top of the 'conde' in 'eval-expo' (and vice versa to de-emphasize a form). The ordering of the 'conde' clauses give us some crude control over how miniKanren explores the search space of terms. Helper Scheme predicate for testing Standard Scheme definition of append. I've wrapped the definition in a 'let' to avoid shadowing Scheme's built-in 'append' definition. 'appendo' doesn't look very Scheme-like, unfortunately. Even the pattern-matching version of 'appendo' doesn't look that much like the Scheme code. With the relational Scheme interpreter written in miniKanren, we can write the *Scheme* definition of 'append', and treat that *function* as a *relation*. This is because the interpreter itself is a relation. Running append "forwards": Running append "backwards:" Scheme-append-under-relational-interpreter-2 results in divergence (looping forever). This seems bad. Aren't there only 6 answers? Whoa! The last answer has a call to 'list' with no arguments, producing the empty list! Because we are running 'append' in the context of the relational Scheme interpreter, the logic variables 'x' and 'y' in the body of the 'letrec' represent *arbitrary Scheme expressions* that evaluate to lists of symbols. Let's look at a few more answers: Sure enough, later answers call 'list', and even use variadic 'lambda' and procedure application. So our Scheme 'append', running in the relational interpreter, is more general than 'appendo'! We can recapture the behavior of 'appendo', in which we restrict the arguments to lists of values (rather than expressions that *evaluate* to lists of values) by a careful use of 'quote' inside the body of the 'letrec': call, we can infer the actual use of 'append' in the call! miniKanren "cheats" by generating a variadic lambda expression whose body returns the "output" list. We can use the 'absento' constraint to keep miniKanren from does not occur in the expression we are trying to infer. expression that also evaluates to the append procedure. We can also infer missing sub-expressions from the definition of 'append'. Here we infer the missing '(car l)' call from the 'else' whose behavior is equivalent to that of '(car l)'. Several subexpressions are quick to infer. Other subexpressions take a very long time to infer. The interpreter cannot (yet) be practically used for example-based program synthesis of programs like 'append', but there may be improvements to the miniKanren implementation, the relational interpreter, and our inference techniques which would make example-based synthesis feasible in practice. We are currently exploring this research area. Scheme programs that evaluate to a given value. For example, here Here is where the real fun begins! thousand Scheme expressions that evaluate to the list '(I love you)'. However, we introduce a new twist. We place the query variable in the body of the 'letrec' in which we have defined 'append'. even though 'append' is not one of the primitives built into the relational Scheme interpreter! Here are a few interesting answers, all of which evaluate to '(I love you)'. This example illustrates how 'append' can be used as a "dummy" value, passed into the variadic function but never used. Scheme expressions that evaluate to themselves. And, of course, we can generate quines in the context of the definition of 'append'. example use 'append'.
(load "interp-with-variadic-lambda.scm") (load "../mk/test-check.scm") (load "../mk/matche.scm") (define member? (lambda (x ls) (not (not (member x ls))))) (let () (define append (lambda (l s) (cond ((null? l) s) (else (cons (car l) (append (cdr l) s)))))) (test "Scheme append-1" (append '(a b c) '(d e)) '(a b c d e)) ) Our normal relational ' appendo ' definition , written in miniKanren . (let () (define appendo (lambda (l s out) (conde ((== '() l) (== s out)) ((fresh (a d res) (== `(,a . ,d) l) (== `(,a . ,res) out) (appendo d s res)))))) (test "appendo-1" (run* (q) (appendo '(a b c) '(d e) q)) '((a b c d e))) (test "appendo-2" (run* (q) (appendo '(a b c) q '(a b c d e))) '((d e))) (test "appendo-3" (run* (x y) (appendo x y '(a b c d e))) '((() (a b c d e)) ((a) (b c d e)) ((a b) (c d e)) ((a b c) (d e)) ((a b c d) (e)) ((a b c d e) ()))) (test "appendo-4" (run 5 (x y z) (appendo x y z)) '((() _.0 _.0) ((_.0) _.1 (_.0 . _.1)) ((_.0 _.1) _.2 (_.0 _.1 . _.2)) ((_.0 _.1 _.2) _.3 (_.0 _.1 _.2 . _.3)) ((_.0 _.1 _.2 _.3) _.4 (_.0 _.1 _.2 _.3 . _.4)))) ) (let () (define appendo (lambda (l s out) (matche (l s out) ((() ,s ,s)) (((,a . ,d) ,s (,a . ,res)) (appendo d s res))))) (test "appendo-1" (run* (q) (appendo '(a b c) '(d e) q)) '((a b c d e))) (test "appendo-2" (run* (q) (appendo '(a b c) q '(a b c d e))) '((d e))) (test "appendo-3" (run* (x y) (appendo x y '(a b c d e))) '((() (a b c d e)) ((a) (b c d e)) ((a b) (c d e)) ((a b c) (d e)) ((a b c d) (e)) ((a b c d e) ()))) (test "appendo-4" (run 5 (x y z) (appendo x y z)) '((() _.0 _.0) ((_.0) _.1 (_.0 . _.1)) ((_.0 _.1) _.2 (_.0 _.1 . _.2)) ((_.0 _.1 _.2) _.3 (_.0 _.1 _.2 . _.3)) ((_.0 _.1 _.2 _.3) _.4 (_.0 _.1 _.2 _.3 . _.4)))) ) (test "Scheme-append-under-relational-interpreter-1" (run* (q) (evalo '(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (append '(a b c) '(d e))) q)) '((a b c d e))) (test "Scheme-append-under-relational-interpreter-2" (run 6 (x y) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (append ,x ,y)) '(a b c d e))) '(('() '(a b c d e)) ('(a) '(b c d e)) ('(a b) '(c d e)) ('(a b c) '(d e)) ('(a b c d) '(e)) ('(a b c d e) '()))) Replacing ' run 6 ' with ' run * ' in Let 's try to generate a seventh answer : (test "Scheme-append-under-relational-interpreter-3" (run 7 (x y) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (append ,x ,y)) '(a b c d e))) '(('() '(a b c d e)) ('(a) '(b c d e)) ('(a b) '(c d e)) ('(a b c) '(d e)) ('(a b c d) '(e)) ('(a b c d e) '()) ('(a b c d e) (list)))) (test "Scheme-append-under-relational-interpreter-4" (run 20 (x y) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (append ,x ,y)) '(a b c d e))) '(('() '(a b c d e)) ('(a) '(b c d e)) ('(a b) '(c d e)) ('(a b c) '(d e)) ('(a b c d) '(e)) ('(a b c d e) '()) ('(a b c d e) (list)) (('() (apply (lambda _.0 '(a b c d e)) '())) (=/= ((_.0 quote))) (sym _.0)) (('(a b c d e) (apply (lambda _.0 _.0) '())) (sym _.0)) (('(a) (apply (lambda _.0 '(b c d e)) '())) (=/= ((_.0 quote))) (sym _.0)) (('(a b) (apply (lambda _.0 '(c d e)) '())) (=/= ((_.0 quote))) (sym _.0)) (('(a b c) (apply (lambda _.0 '(d e)) '())) (=/= ((_.0 quote))) (sym _.0)) (('(a b c d) (apply (lambda _.0 '(e)) '())) (=/= ((_.0 quote))) (sym _.0)) (('(a b c d e) (apply (lambda _.0 '()) '())) (=/= ((_.0 quote))) (sym _.0)) ('(a b c d) (list 'e)) (('(a b c d) (apply (lambda _.0 _.0) '(e))) (sym _.0)) (('() (apply (lambda _.0 '(a b c d e)) '(_.1))) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))) (('(a) (apply (lambda _.0 '(b c d e)) '(_.1))) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))) (('(a b) (apply (lambda _.0 '(c d e)) '(_.1))) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))) (('(a b c) (apply (lambda _.0 '(d e)) '(_.1))) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))))) (test "Scheme-append-under-relational-interpreter-5" (run* (x y) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (append (quote ,x) (quote ,y))) '(a b c d e))) '((() (a b c d e)) ((a) (b c d e)) ((a b) (c d e)) ((a b c) (d e)) ((a b c d) (e)) ((a b c d e) ()))) In addition to inferring the two list arguments in an ' append ' Our first attempt to infer the use of ' append ' is unsuccessful . (test "infer-append-use-1" (run 1 (q) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (,q '(a b c) '(d e))) '(a b c d e))) '(((lambda _.0 '(a b c d e)) (=/= ((_.0 quote))) (sym _.0)))) cheating . The constraint ' ( absento ' a q ) ' ensures that the symbol ' a'---which occurs in both the input to the call and the This results in the expected answer , ' append ' , and a second (test "infer-append-use-2" (run 2 (q) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) (,q '(a b c) '(d e))) '(a b c d e)) (absento 'a q)) '(append ((apply (lambda _.0 append) '()) (=/= ((_.0 a)) ((_.0 append))) (sym _.0)))) branch of the ' if ' expression . The second answer is an expression (test "infer-car-1" (run 2 (q) (absento 'a q) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons ,q (append (cdr l) s)))))) (append '(a b c) '(d e))) '(a b c d e))) '((car l) ((apply (lambda _.0 (car l)) s) (=/= ((_.0 a)) ((_.0 car)) ((_.0 l))) (sym _.0)))) One fun thing we can do with the relational interpreter is generate are ten Scheme expressions that evaluate to the list ' ( I love you ) ' . (test "I-love-you-1" (run 10 (q) (evalo q '(I love you))) '('(I love you) ((apply (lambda _.0 '(I love you)) '()) (=/= ((_.0 quote))) (sym _.0)) ((apply (lambda _.0 '(I love you)) '(_.1)) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))) ((apply (lambda _.0 '(I love you)) '(_.1 _.2)) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1) (closure _.2))) ((apply (lambda (_.0) '(I love you)) '(_.1)) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))) ((apply (lambda (_.0) _.0) '((I love you))) (sym _.0)) (list 'I 'love 'you) (((lambda _.0 '(I love you))) (=/= ((_.0 quote))) (sym _.0)) ((apply (lambda _.0 '(I love you)) '(_.1 _.2 _.3)) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1) (closure _.2) (closure _.3))) (((lambda _.0 '(I love you)) '_.1) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))))) We can run a similar query to the one above , generating one Therefore , miniKanren is free to infer expressions that use ' append ' , (define I-love-you-append (run 1000 (q) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) ,q) '(I love you)))) (test "I-love-you-append-1" (member? '(apply append '((I love) (you))) I-love-you-append) #t) (test "I-love-you-append-2" (member? '((apply (lambda _.0 (apply append '((I love) (you)))) '()) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 quote))) (sym _.0)) I-love-you-append) #t) (test "I-love-you-append-3" (member? '(((lambda _.0 '(I love you)) append append append append) (=/= ((_.0 quote))) (sym _.0)) I-love-you-append) #t) (test "I-love-you-append-4" (member? '((apply (lambda _.0 (apply append '((I) (love you)))) '()) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 quote))) (sym _.0)) I-love-you-append) #t) (test "I-love-you-append-5" (member? '((apply append (apply (lambda _.0 '((I love) (you))) '())) (=/= ((_.0 quote))) (sym _.0)) I-love-you-append) #t) (test "I-love-you-append-6" (member? '((apply (lambda _.0 (car _.0)) '((I love you))) (=/= ((_.0 car))) (sym _.0)) I-love-you-append) #t) (test "I-love-you-append-7" (member? '(((lambda _.0 '(I love you)) append append append append) (=/= ((_.0 quote))) (sym _.0)) I-love-you-append) #t) Our relational interpreter can also generate quines , which are (test "simple quines" (run 5 (q) (evalo q q)) '(#t #f ((apply (lambda _.0 (list 'apply (apply (lambda (_.1) _.1) _.0) (list 'quote _.0))) '((lambda _.0 (list 'apply (apply (lambda (_.1) _.1) _.0) (list 'quote _.0))))) (=/= ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (sym _.0 _.1)) ((apply (lambda _.0 (list (apply (lambda _.1 'apply) '()) (apply (lambda (_.2) _.2) _.0) (list 'quote _.0))) '((lambda _.0 (list (apply (lambda _.1 'apply) '()) (apply (lambda (_.2) _.2) _.0) (list 'quote _.0))))) (=/= ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 quote)) ((_.2 closure))) (sym _.0 _.1 _.2)) ((apply (lambda _.0 (list 'apply _.0 (list 'quote _.0))) '(lambda _.0 (list 'apply _.0 (list 'quote _.0)))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)))) (define quines-in-context-of-append (run 60 (q) (evalo `(letrec ((append (lambda (l s) (if (null? l) s (cons (car l) (append (cdr l) s)))))) ,q) q))) Here are a few of the generated quines . All but the first and last (test "quines-in-context-of-append-1" (member? '((apply (lambda _.0 (list 'apply _.0 (list 'quote _.0))) '(lambda _.0 (list 'apply _.0 (list 'quote _.0)))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-2" (member? '((apply (lambda _.0 (list 'apply (apply append _.0) (list 'quote _.0))) '(() (lambda _.0 (list 'apply (apply append _.0) (list 'quote _.0))))) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-3" (member? '((apply (lambda _.0 (list 'apply (apply append _.0) ((lambda _.1 _.1) 'quote _.0))) '(() (lambda _.0 (list 'apply (apply append _.0) ((lambda _.1 _.1) 'quote _.0))))) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (sym _.0 _.1)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-4" (member? '((apply (lambda _.0 (list 'apply (apply append _.0) (apply (lambda _.1 (list 'quote _.1)) _.0))) '(() (lambda _.0 (list 'apply (apply append _.0) (apply (lambda _.1 (list 'quote _.1)) _.0))))) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (sym _.0 _.1)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-5" (member? '((apply (lambda _.0 (list (apply (lambda _.1 'apply) _.0) (apply append _.0) (list 'quote _.0))) '(() (lambda _.0 (list (apply (lambda _.1 'apply) _.0) (apply append _.0) (list 'quote _.0))))) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 quote))) (sym _.0 _.1)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-6" (member? '((apply (lambda _.0 (list 'apply (apply append _.0) (apply (lambda _.1 (list 'quote _.0)) _.0))) '(() (lambda _.0 (list 'apply (apply append _.0) (apply (lambda _.1 (list 'quote _.0)) _.0))))) (=/= ((_.0 _.1)) ((_.0 append)) ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (sym _.0 _.1)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-7" (member? '((apply (lambda _.0 (list 'apply (apply append _.0) (list 'quote (apply (lambda _.1 _.1) _.0)))) '(() (lambda _.0 (list 'apply (apply append _.0) (list 'quote (apply (lambda _.1 _.1) _.0)))))) (=/= ((_.0 append)) ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (sym _.0 _.1)) quines-in-context-of-append) #t) (test "quines-in-context-of-append-8" (member? '((apply (lambda _.0 (list 'apply (apply (lambda (_.1) _.1) _.0) (apply (lambda _.2 ((lambda _.3 _.3) 'quote _.2)) _.0))) '((lambda _.0 (list 'apply (apply (lambda (_.1) _.1) _.0) (apply (lambda _.2 ((lambda _.3 _.3) 'quote _.2)) _.0))))) (=/= ((_.0 apply)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.2 closure)) ((_.2 lambda)) ((_.2 quote)) ((_.3 closure))) (sym _.0 _.1 _.2 _.3)) quines-in-context-of-append) #t)
89b46d81f2d8866aef22942e06420b9caa2dffa3706310901a2cd65602876d99
dakrone/clojure-opennlp
treebank.clj
(ns opennlp.test.treebank (:use [opennlp.treebank]) (:use [clojure.test]) (:use [opennlp.nlp :only [make-tokenizer make-pos-tagger]]) (:import [java.io File FileNotFoundException])) (def tokenize (make-tokenizer "models/en-token.bin")) (def pos-tag (make-pos-tagger "models/en-pos-maxent.bin")) (def chunker (make-treebank-chunker "models/en-chunker.bin")) (deftest chunker-test (is (= (chunker (pos-tag (tokenize (str "The override system is meant to" " deactivate the accelerator when" " the brake pedal is pressed.")))) '({:phrase ["The" "override" "system"] :tag "NP"} {:phrase ["is" "meant" "to" "deactivate"] :tag "VP"} {:phrase ["the" "accelerator"] :tag "NP"} {:phrase ["when"] :tag "ADVP"} {:phrase ["the" "brake" "pedal"] :tag "NP"} {:phrase ["is" "pressed"] :tag "VP"})))) (deftest no-model-file-test (is (thrown? FileNotFoundException (make-treebank-chunker "nonexistantfile"))) (is (thrown? FileNotFoundException (make-treebank-parser "nonexistantfile")))) (deftest parser-test-normal (try (let [parser (make-treebank-parser "parser-model/en-parser-chunking.bin")] (is (= (parser ["This is a sentence ."]) [(str "(TOP (S (NP (DT This)) (VP (VBZ is) (NP (DT a)" " (NN sentence))) (. .) ))")])) (is (= (make-tree (first (parser ["This is a sentence ."]))) '{:tag TOP :chunk ( {:tag S :chunk ({:tag NP :chunk ({:tag DT :chunk ("This")})} {:tag VP :chunk ({:tag VBZ :chunk ("is")} {:tag NP :chunk ({:tag DT :chunk ("a")} {:tag NN :chunk ("sentence")})})} {:tag . :chunk (".")})})}))) (catch FileNotFoundException e (println "Unable to execute treebank-parser tests." "Download the model files to $PROJECT_ROOT/parser-models.")))) (deftest parser-test-with-bad-chars (try (let [parser (make-treebank-parser "parser-model/en-parser-chunking.bin")] (is (= (parser ["2:30 isn't bad"]) ["(TOP (NP (CD 2:30) (RB isn't) (JJ bad)) )"])) (is (= (make-tree (first (parser ["2:30 isn't bad"]))) '{:tag TOP, :chunk ({:tag NP, :chunk ({:tag CD, :chunk ("2:30")} {:tag RB, :chunk ("isn't")} {:tag JJ, :chunk ("bad")})}) }))) (catch FileNotFoundException e (println "Unable to execute treebank-parser tests." "Download the model files to $PROJECT_ROOT/parser-models.")))) #_(deftest treebank-coref-test (try (let [tbl (make-treebank-linker "coref") s (parser ["Mary said she would help me ." "I told her I didn't need her help ."])] (is (= [] (tbl s)))) (catch FileNotFoundException e (println "Unable to execute treebank-parser tests." "Download the model files to $PROJECT_ROOT/parser-models."))))
null
https://raw.githubusercontent.com/dakrone/clojure-opennlp/17627c13fe261e62e6c7ff0521fba2b6d92ec091/test/opennlp/test/treebank.clj
clojure
(ns opennlp.test.treebank (:use [opennlp.treebank]) (:use [clojure.test]) (:use [opennlp.nlp :only [make-tokenizer make-pos-tagger]]) (:import [java.io File FileNotFoundException])) (def tokenize (make-tokenizer "models/en-token.bin")) (def pos-tag (make-pos-tagger "models/en-pos-maxent.bin")) (def chunker (make-treebank-chunker "models/en-chunker.bin")) (deftest chunker-test (is (= (chunker (pos-tag (tokenize (str "The override system is meant to" " deactivate the accelerator when" " the brake pedal is pressed.")))) '({:phrase ["The" "override" "system"] :tag "NP"} {:phrase ["is" "meant" "to" "deactivate"] :tag "VP"} {:phrase ["the" "accelerator"] :tag "NP"} {:phrase ["when"] :tag "ADVP"} {:phrase ["the" "brake" "pedal"] :tag "NP"} {:phrase ["is" "pressed"] :tag "VP"})))) (deftest no-model-file-test (is (thrown? FileNotFoundException (make-treebank-chunker "nonexistantfile"))) (is (thrown? FileNotFoundException (make-treebank-parser "nonexistantfile")))) (deftest parser-test-normal (try (let [parser (make-treebank-parser "parser-model/en-parser-chunking.bin")] (is (= (parser ["This is a sentence ."]) [(str "(TOP (S (NP (DT This)) (VP (VBZ is) (NP (DT a)" " (NN sentence))) (. .) ))")])) (is (= (make-tree (first (parser ["This is a sentence ."]))) '{:tag TOP :chunk ( {:tag S :chunk ({:tag NP :chunk ({:tag DT :chunk ("This")})} {:tag VP :chunk ({:tag VBZ :chunk ("is")} {:tag NP :chunk ({:tag DT :chunk ("a")} {:tag NN :chunk ("sentence")})})} {:tag . :chunk (".")})})}))) (catch FileNotFoundException e (println "Unable to execute treebank-parser tests." "Download the model files to $PROJECT_ROOT/parser-models.")))) (deftest parser-test-with-bad-chars (try (let [parser (make-treebank-parser "parser-model/en-parser-chunking.bin")] (is (= (parser ["2:30 isn't bad"]) ["(TOP (NP (CD 2:30) (RB isn't) (JJ bad)) )"])) (is (= (make-tree (first (parser ["2:30 isn't bad"]))) '{:tag TOP, :chunk ({:tag NP, :chunk ({:tag CD, :chunk ("2:30")} {:tag RB, :chunk ("isn't")} {:tag JJ, :chunk ("bad")})}) }))) (catch FileNotFoundException e (println "Unable to execute treebank-parser tests." "Download the model files to $PROJECT_ROOT/parser-models.")))) #_(deftest treebank-coref-test (try (let [tbl (make-treebank-linker "coref") s (parser ["Mary said she would help me ." "I told her I didn't need her help ."])] (is (= [] (tbl s)))) (catch FileNotFoundException e (println "Unable to execute treebank-parser tests." "Download the model files to $PROJECT_ROOT/parser-models."))))
15653f23be7189cc9dfffa6e1a4f12ce8721dad4c1ffe633b349f22197aea5ab
faylang/fay
DoLet2.hs
module DoLet2 where import FFI main = do print 1 let [a,b] = [3] print a
null
https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/tests/DoLet2.hs
haskell
module DoLet2 where import FFI main = do print 1 let [a,b] = [3] print a
eb04bbe5069c8d86a5326e2a1ed10bb47a823a0060ee0beca9afc0f31e5527c0
tnelson/Forge
blah.rkt
#lang forge sig Elem {} pred main { some Elem * Elem -> Elem } run main for exactly 2 Elem
null
https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/examples/blah.rkt
racket
#lang forge sig Elem {} pred main { some Elem * Elem -> Elem } run main for exactly 2 Elem
0d631efb5faf4e3377e702d627d75b2d9e8738ef5542d15fca46277b9d059196
c-cube/ocaml-containers
CCMap.ml
(* This file is free software, part of containers. See file "license" for more details. *) (** {1 Extensions of Standard Map} *) type 'a iter = ('a -> unit) -> unit type 'a printer = Format.formatter -> 'a -> unit module type OrderedType = Map.OrderedType module type S = sig include Map.S val get : key -> 'a t -> 'a option (** [get k m] returns [Some v] if the current binding of [k] in [m] is [v], or [None] if the key [k] is not present. Safe version of {!find}. *) val get_or : key -> 'a t -> default:'a -> 'a * [ get_or k m ~default ] returns the value associated to [ k ] if present , and returns [ default ] otherwise ( if [ k ] does n't belong in [ m ] ) . @since 0.16 and returns [default] otherwise (if [k] doesn't belong in [m]). @since 0.16 *) val update : key -> ('a option -> 'a option) -> 'a t -> 'a t (** [update k f m] calls [f (Some v)] if [find k m = v], otherwise it calls [f None]. In any case, if the result is [None] [k] is removed from [m], and if the result is [Some v'] then [add k v' m] is returned. *) val choose_opt : 'a t -> (key * 'a) option * [ choose_opt m ] returns one binding of the given map [ m ] , or [ None ] if [ m ] is empty . Safe version of { ! choose } . @since 1.5 Safe version of {!choose}. @since 1.5 *) val min_binding_opt : 'a t -> (key * 'a) option * [ min_binding_opt m ] returns the smallest binding of the given map [ m ] , or [ None ] if [ m ] is empty . Safe version of { ! min_binding } . @since 1.5 or [None] if [m] is empty. Safe version of {!min_binding}. @since 1.5 *) val max_binding_opt : 'a t -> (key * 'a) option * [ max_binding_opt m ] returns the largest binding of the given map [ m ] , or [ None ] if [ m ] is empty . Safe version of { ! max_binding } . @since 1.5 or [None] if [m] is empty. Safe version of {!max_binding}. @since 1.5 *) val find_opt : key -> 'a t -> 'a option * [ find_opt k m ] returns [ Some v ] if the current binding of [ k ] in [ m ] is [ v ] , or [ None ] if the key [ k ] is not present . Safe version of { ! find } . @since 1.5 or [None] if the key [k] is not present. Safe version of {!find}. @since 1.5 *) val find_first : (key -> bool) -> 'a t -> key * 'a * [ find_first f m ] where [ f ] is a monotonically increasing function , returns the binding of [ m ] with the lowest key [ k ] such that [ f k ] , or raises [ Not_found ] if no such key exists . See { ! Map . S.find_first } . @since 1.5 with the lowest key [k] such that [f k], or raises [Not_found] if no such key exists. See {!Map.S.find_first}. @since 1.5 *) val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option * [ f m ] where [ f ] is a monotonically increasing function , returns an option containing the binding of [ m ] with the lowest key [ k ] such that [ f k ] , or [ None ] if no such key exists . Safe version of { ! find_first } . @since 1.5 the binding of [m] with the lowest key [k] such that [f k], or [None] if no such key exists. Safe version of {!find_first}. @since 1.5 *) val merge_safe : f:(key -> [ `Left of 'a | `Right of 'b | `Both of 'a * 'b ] -> 'c option) -> 'a t -> 'b t -> 'c t * [ merge_safe ~f a b ] merges the maps [ a ] and [ b ] together . @since 0.17 @since 0.17 *) val add_seq : 'a t -> (key * 'a) Seq.t -> 'a t * [ add_seq m seq ] adds the given [ Seq.t ] of bindings to the map [ m ] . Like { ! add_list } . Renamed from [ add_std_seq ] since 3.0 . @since 3.0 Like {!add_list}. Renamed from [add_std_seq] since 3.0. @since 3.0 *) val add_seq_with : f:(key -> 'a -> 'a -> 'a) -> 'a t -> (key * 'a) Seq.t -> 'a t * [ add_seq ~f m l ] adds the given seq [ l ] of bindings to the map [ m ] , using [ f ] to combine values that have the same key . @since 3.3 using [f] to combine values that have the same key. @since 3.3 *) val of_seq : (key * 'a) Seq.t -> 'a t * [ of_seq seq ] builds a map from the given [ Seq.t ] of bindings . Like { ! of_list } . Renamed from [ of_std_seq ] since 3.0 . @since 3.0 Like {!of_list}. Renamed from [of_std_seq] since 3.0. @since 3.0 *) val of_seq_with : f:(key -> 'a -> 'a -> 'a) -> (key * 'a) Seq.t -> 'a t * [ ~f l ] builds a map from the given seq [ l ] of bindings [ k_i - > v_i ] , added in order using { ! add } . If a key occurs several times , all its bindings are combined using the function [ f ] , with [ f key v1 v2 ] being called with [ v1 ] occurring later in the seq than [ v2 ] . @since 3.3 added in order using {!add}. If a key occurs several times, all its bindings are combined using the function [f], with [f key v1 v2] being called with [v1] occurring later in the seq than [v2]. @since 3.3 *) val add_iter : 'a t -> (key * 'a) iter -> 'a t * [ add_iter m iter ] adds the given [ iter ] of bindings to the map [ m ] . Like { ! add_list } . @since 2.8 Like {!add_list}. @since 2.8 *) val add_iter_with : f:(key -> 'a -> 'a -> 'a) -> 'a t -> (key * 'a) iter -> 'a t * [ add_iter ~f m l ] adds the given iter [ l ] of bindings to the map [ m ] , using [ f ] to combine values that have the same key . @since 3.3 using [f] to combine values that have the same key. @since 3.3 *) val of_iter : (key * 'a) iter -> 'a t * [ of_iter iter ] builds a map from the given [ iter ] of bindings . Like { ! of_list } . @since 2.8 Like {!of_list}. @since 2.8 *) val of_iter_with : f:(key -> 'a -> 'a -> 'a) -> (key * 'a) iter -> 'a t * [ of_iter_with ~f l ] builds a map from the given iter [ l ] of bindings [ k_i - > v_i ] , added in order using { ! add } . If a key occurs several times , all its bindings are combined using the function [ f ] , with [ f key v1 v2 ] being called with [ v1 ] occurring later in the iter than [ v2 ] . @since 3.3 added in order using {!add}. If a key occurs several times, all its bindings are combined using the function [f], with [f key v1 v2] being called with [v1] occurring later in the iter than [v2]. @since 3.3 *) val to_iter : 'a t -> (key * 'a) iter * [ to_iter m ] iterates on the whole map [ m ] , creating an [ iter ] of bindings . Like { ! to_list } . @since 2.8 Like {!to_list}. @since 2.8 *) val of_list : (key * 'a) list -> 'a t (** [of_list l] builds a map from the given list [l] of bindings [k_i -> v_i], added in order using {!add}. If a key occurs several times, only its last binding will be present in the result. *) val of_list_with : f:(key -> 'a -> 'a -> 'a) -> (key * 'a) list -> 'a t * [ of_list_with ~f l ] builds a map from the given list [ l ] of bindings [ k_i - > v_i ] , added in order using { ! add } . If a key occurs several times , all its bindings are combined using the function [ f ] , with [ f key v1 v2 ] being called with [ v1 ] occurring later in the list than [ v2 ] . @since 3.3 added in order using {!add}. If a key occurs several times, all its bindings are combined using the function [f], with [f key v1 v2] being called with [v1] occurring later in the list than [v2]. @since 3.3 *) val add_list : 'a t -> (key * 'a) list -> 'a t * [ add_list m l ] adds the given list [ l ] of bindings to the map [ m ] . @since 0.14 @since 0.14 *) val add_list_with : f:(key -> 'a -> 'a -> 'a) -> 'a t -> (key * 'a) list -> 'a t * [ add_list ~f m l ] adds the given list [ l ] of bindings to the map [ m ] , using [ f ] to combine values that have the same key . @since 3.3 using [f] to combine values that have the same key. @since 3.3 *) val keys : _ t -> key iter * [ keys m ] iterates on the keys of [ m ] only , creating an [ iter ] of keys . @since 0.15 @since 0.15 *) val values : 'a t -> 'a iter * [ values m ] iterates on the values of [ m ] only , creating an [ iter ] of values . @since 0.15 @since 0.15 *) val to_list : 'a t -> (key * 'a) list (** [to_list m] builds a list of the bindings of the given map [m]. The order is unspecified. *) val pp : ?pp_start:unit printer -> ?pp_stop:unit printer -> ?pp_arrow:unit printer -> ?pp_sep:unit printer -> key printer -> 'a printer -> 'a t printer (** [pp ?pp_start ?pp_stop ?pp_arrow ?pp_sep pp_key pp_v m] pretty-prints the contents of the map. *) end module Make (O : Map.OrderedType) = struct module M = Map.Make (O) (* backport functions from recent stdlib. they will be shadowed by inclusion of [S] if present. *) let union f a b = M.merge (fun k v1 v2 -> match v1, v2 with | None, None -> assert false | None, (Some _ as r) -> r | (Some _ as r), None -> r | Some v1, Some v2 -> f k v1 v2) a b let update k f m = let x = try f (Some (M.find k m)) with Not_found -> f None in match x with | None -> M.remove k m | Some v' -> M.add k v' m let choose_opt m = try Some (M.choose m) with Not_found -> None let find_opt k m = try Some (M.find k m) with Not_found -> None let max_binding_opt m = try Some (M.max_binding m) with Not_found -> None let min_binding_opt m = try Some (M.min_binding m) with Not_found -> None exception Find_binding_exit let find_first_opt f m = let res = ref None in try M.iter (fun k v -> if f k then ( res := Some (k, v); raise Find_binding_exit )) m; None with Find_binding_exit -> !res let find_first f m = match find_first_opt f m with | None -> raise Not_found | Some (k, v) -> k, v (* linear time, must traverse the whole map… *) let find_last_opt f m = let res = ref None in M.iter (fun k v -> if f k then res := Some (k, v)) m; !res let find_last f m = match find_last_opt f m with | None -> raise Not_found | Some (k, v) -> k, v = = = include M. This will shadow some values depending on 's current version = = = This will shadow some values depending on OCaml's current version === *) include M let get = find_opt let get_or k m ~default = try find k m with Not_found -> default let merge_safe ~f a b = merge (fun k v1 v2 -> match v1, v2 with | None, None -> assert false | Some v1, None -> f k (`Left v1) | None, Some v2 -> f k (`Right v2) | Some v1, Some v2 -> f k (`Both (v1, v2))) a b let add_seq m s = let m = ref m in Seq.iter (fun (k, v) -> m := add k v !m) s; !m let add_seq_with ~f m s = let combine k v = function | None -> Some v | Some v0 -> Some (f k v v0) in Seq.fold_left (fun m (k, v) -> update k (combine k v) m) m s let of_seq s = add_seq empty s let of_seq_with ~f s = add_seq_with ~f empty s let add_iter m s = let m = ref m in s (fun (k, v) -> m := add k v !m); !m let add_iter_with ~f m s = let combine k v = function | None -> Some v | Some v0 -> Some (f k v v0) in let m = ref m in s (fun (k, v) -> m := update k (combine k v) !m); !m let of_iter s = add_iter empty s let of_iter_with ~f s = add_iter_with ~f empty s let to_iter m yield = iter (fun k v -> yield (k, v)) m let keys m yield = iter (fun k _ -> yield k) m let values m yield = iter (fun _ v -> yield v) m let add_list m l = List.fold_left (fun m (k, v) -> add k v m) m l let add_list_with ~f m l = let combine k v = function | None -> Some v | Some v0 -> Some (f k v v0) in List.fold_left (fun m (k, v) -> update k (combine k v) m) m l let of_list l = add_list empty l let of_list_with ~f l = add_list_with ~f empty l let to_list m = fold (fun k v acc -> (k, v) :: acc) m [] let pp ?(pp_start = fun _ () -> ()) ?(pp_stop = fun _ () -> ()) ?(pp_arrow = fun fmt () -> Format.fprintf fmt "@ -> ") ?(pp_sep = fun fmt () -> Format.fprintf fmt ",@ ") pp_k pp_v fmt m = pp_start fmt (); let first = ref true in iter (fun k v -> if !first then first := false else pp_sep fmt (); pp_k fmt k; pp_arrow fmt (); pp_v fmt v) m; pp_stop fmt () end
null
https://raw.githubusercontent.com/c-cube/ocaml-containers/69f2805f1073c4ebd1063bbd58380d17e62f6324/src/core/CCMap.ml
ocaml
This file is free software, part of containers. See file "license" for more details. * {1 Extensions of Standard Map} * [get k m] returns [Some v] if the current binding of [k] in [m] is [v], or [None] if the key [k] is not present. Safe version of {!find}. * [update k f m] calls [f (Some v)] if [find k m = v], otherwise it calls [f None]. In any case, if the result is [None] [k] is removed from [m], and if the result is [Some v'] then [add k v' m] is returned. * [of_list l] builds a map from the given list [l] of bindings [k_i -> v_i], added in order using {!add}. If a key occurs several times, only its last binding will be present in the result. * [to_list m] builds a list of the bindings of the given map [m]. The order is unspecified. * [pp ?pp_start ?pp_stop ?pp_arrow ?pp_sep pp_key pp_v m] pretty-prints the contents of the map. backport functions from recent stdlib. they will be shadowed by inclusion of [S] if present. linear time, must traverse the whole map…
type 'a iter = ('a -> unit) -> unit type 'a printer = Format.formatter -> 'a -> unit module type OrderedType = Map.OrderedType module type S = sig include Map.S val get : key -> 'a t -> 'a option val get_or : key -> 'a t -> default:'a -> 'a * [ get_or k m ~default ] returns the value associated to [ k ] if present , and returns [ default ] otherwise ( if [ k ] does n't belong in [ m ] ) . @since 0.16 and returns [default] otherwise (if [k] doesn't belong in [m]). @since 0.16 *) val update : key -> ('a option -> 'a option) -> 'a t -> 'a t val choose_opt : 'a t -> (key * 'a) option * [ choose_opt m ] returns one binding of the given map [ m ] , or [ None ] if [ m ] is empty . Safe version of { ! choose } . @since 1.5 Safe version of {!choose}. @since 1.5 *) val min_binding_opt : 'a t -> (key * 'a) option * [ min_binding_opt m ] returns the smallest binding of the given map [ m ] , or [ None ] if [ m ] is empty . Safe version of { ! min_binding } . @since 1.5 or [None] if [m] is empty. Safe version of {!min_binding}. @since 1.5 *) val max_binding_opt : 'a t -> (key * 'a) option * [ max_binding_opt m ] returns the largest binding of the given map [ m ] , or [ None ] if [ m ] is empty . Safe version of { ! max_binding } . @since 1.5 or [None] if [m] is empty. Safe version of {!max_binding}. @since 1.5 *) val find_opt : key -> 'a t -> 'a option * [ find_opt k m ] returns [ Some v ] if the current binding of [ k ] in [ m ] is [ v ] , or [ None ] if the key [ k ] is not present . Safe version of { ! find } . @since 1.5 or [None] if the key [k] is not present. Safe version of {!find}. @since 1.5 *) val find_first : (key -> bool) -> 'a t -> key * 'a * [ find_first f m ] where [ f ] is a monotonically increasing function , returns the binding of [ m ] with the lowest key [ k ] such that [ f k ] , or raises [ Not_found ] if no such key exists . See { ! Map . S.find_first } . @since 1.5 with the lowest key [k] such that [f k], or raises [Not_found] if no such key exists. See {!Map.S.find_first}. @since 1.5 *) val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option * [ f m ] where [ f ] is a monotonically increasing function , returns an option containing the binding of [ m ] with the lowest key [ k ] such that [ f k ] , or [ None ] if no such key exists . Safe version of { ! find_first } . @since 1.5 the binding of [m] with the lowest key [k] such that [f k], or [None] if no such key exists. Safe version of {!find_first}. @since 1.5 *) val merge_safe : f:(key -> [ `Left of 'a | `Right of 'b | `Both of 'a * 'b ] -> 'c option) -> 'a t -> 'b t -> 'c t * [ merge_safe ~f a b ] merges the maps [ a ] and [ b ] together . @since 0.17 @since 0.17 *) val add_seq : 'a t -> (key * 'a) Seq.t -> 'a t * [ add_seq m seq ] adds the given [ Seq.t ] of bindings to the map [ m ] . Like { ! add_list } . Renamed from [ add_std_seq ] since 3.0 . @since 3.0 Like {!add_list}. Renamed from [add_std_seq] since 3.0. @since 3.0 *) val add_seq_with : f:(key -> 'a -> 'a -> 'a) -> 'a t -> (key * 'a) Seq.t -> 'a t * [ add_seq ~f m l ] adds the given seq [ l ] of bindings to the map [ m ] , using [ f ] to combine values that have the same key . @since 3.3 using [f] to combine values that have the same key. @since 3.3 *) val of_seq : (key * 'a) Seq.t -> 'a t * [ of_seq seq ] builds a map from the given [ Seq.t ] of bindings . Like { ! of_list } . Renamed from [ of_std_seq ] since 3.0 . @since 3.0 Like {!of_list}. Renamed from [of_std_seq] since 3.0. @since 3.0 *) val of_seq_with : f:(key -> 'a -> 'a -> 'a) -> (key * 'a) Seq.t -> 'a t * [ ~f l ] builds a map from the given seq [ l ] of bindings [ k_i - > v_i ] , added in order using { ! add } . If a key occurs several times , all its bindings are combined using the function [ f ] , with [ f key v1 v2 ] being called with [ v1 ] occurring later in the seq than [ v2 ] . @since 3.3 added in order using {!add}. If a key occurs several times, all its bindings are combined using the function [f], with [f key v1 v2] being called with [v1] occurring later in the seq than [v2]. @since 3.3 *) val add_iter : 'a t -> (key * 'a) iter -> 'a t * [ add_iter m iter ] adds the given [ iter ] of bindings to the map [ m ] . Like { ! add_list } . @since 2.8 Like {!add_list}. @since 2.8 *) val add_iter_with : f:(key -> 'a -> 'a -> 'a) -> 'a t -> (key * 'a) iter -> 'a t * [ add_iter ~f m l ] adds the given iter [ l ] of bindings to the map [ m ] , using [ f ] to combine values that have the same key . @since 3.3 using [f] to combine values that have the same key. @since 3.3 *) val of_iter : (key * 'a) iter -> 'a t * [ of_iter iter ] builds a map from the given [ iter ] of bindings . Like { ! of_list } . @since 2.8 Like {!of_list}. @since 2.8 *) val of_iter_with : f:(key -> 'a -> 'a -> 'a) -> (key * 'a) iter -> 'a t * [ of_iter_with ~f l ] builds a map from the given iter [ l ] of bindings [ k_i - > v_i ] , added in order using { ! add } . If a key occurs several times , all its bindings are combined using the function [ f ] , with [ f key v1 v2 ] being called with [ v1 ] occurring later in the iter than [ v2 ] . @since 3.3 added in order using {!add}. If a key occurs several times, all its bindings are combined using the function [f], with [f key v1 v2] being called with [v1] occurring later in the iter than [v2]. @since 3.3 *) val to_iter : 'a t -> (key * 'a) iter * [ to_iter m ] iterates on the whole map [ m ] , creating an [ iter ] of bindings . Like { ! to_list } . @since 2.8 Like {!to_list}. @since 2.8 *) val of_list : (key * 'a) list -> 'a t val of_list_with : f:(key -> 'a -> 'a -> 'a) -> (key * 'a) list -> 'a t * [ of_list_with ~f l ] builds a map from the given list [ l ] of bindings [ k_i - > v_i ] , added in order using { ! add } . If a key occurs several times , all its bindings are combined using the function [ f ] , with [ f key v1 v2 ] being called with [ v1 ] occurring later in the list than [ v2 ] . @since 3.3 added in order using {!add}. If a key occurs several times, all its bindings are combined using the function [f], with [f key v1 v2] being called with [v1] occurring later in the list than [v2]. @since 3.3 *) val add_list : 'a t -> (key * 'a) list -> 'a t * [ add_list m l ] adds the given list [ l ] of bindings to the map [ m ] . @since 0.14 @since 0.14 *) val add_list_with : f:(key -> 'a -> 'a -> 'a) -> 'a t -> (key * 'a) list -> 'a t * [ add_list ~f m l ] adds the given list [ l ] of bindings to the map [ m ] , using [ f ] to combine values that have the same key . @since 3.3 using [f] to combine values that have the same key. @since 3.3 *) val keys : _ t -> key iter * [ keys m ] iterates on the keys of [ m ] only , creating an [ iter ] of keys . @since 0.15 @since 0.15 *) val values : 'a t -> 'a iter * [ values m ] iterates on the values of [ m ] only , creating an [ iter ] of values . @since 0.15 @since 0.15 *) val to_list : 'a t -> (key * 'a) list val pp : ?pp_start:unit printer -> ?pp_stop:unit printer -> ?pp_arrow:unit printer -> ?pp_sep:unit printer -> key printer -> 'a printer -> 'a t printer end module Make (O : Map.OrderedType) = struct module M = Map.Make (O) let union f a b = M.merge (fun k v1 v2 -> match v1, v2 with | None, None -> assert false | None, (Some _ as r) -> r | (Some _ as r), None -> r | Some v1, Some v2 -> f k v1 v2) a b let update k f m = let x = try f (Some (M.find k m)) with Not_found -> f None in match x with | None -> M.remove k m | Some v' -> M.add k v' m let choose_opt m = try Some (M.choose m) with Not_found -> None let find_opt k m = try Some (M.find k m) with Not_found -> None let max_binding_opt m = try Some (M.max_binding m) with Not_found -> None let min_binding_opt m = try Some (M.min_binding m) with Not_found -> None exception Find_binding_exit let find_first_opt f m = let res = ref None in try M.iter (fun k v -> if f k then ( res := Some (k, v); raise Find_binding_exit )) m; None with Find_binding_exit -> !res let find_first f m = match find_first_opt f m with | None -> raise Not_found | Some (k, v) -> k, v let find_last_opt f m = let res = ref None in M.iter (fun k v -> if f k then res := Some (k, v)) m; !res let find_last f m = match find_last_opt f m with | None -> raise Not_found | Some (k, v) -> k, v = = = include M. This will shadow some values depending on 's current version = = = This will shadow some values depending on OCaml's current version === *) include M let get = find_opt let get_or k m ~default = try find k m with Not_found -> default let merge_safe ~f a b = merge (fun k v1 v2 -> match v1, v2 with | None, None -> assert false | Some v1, None -> f k (`Left v1) | None, Some v2 -> f k (`Right v2) | Some v1, Some v2 -> f k (`Both (v1, v2))) a b let add_seq m s = let m = ref m in Seq.iter (fun (k, v) -> m := add k v !m) s; !m let add_seq_with ~f m s = let combine k v = function | None -> Some v | Some v0 -> Some (f k v v0) in Seq.fold_left (fun m (k, v) -> update k (combine k v) m) m s let of_seq s = add_seq empty s let of_seq_with ~f s = add_seq_with ~f empty s let add_iter m s = let m = ref m in s (fun (k, v) -> m := add k v !m); !m let add_iter_with ~f m s = let combine k v = function | None -> Some v | Some v0 -> Some (f k v v0) in let m = ref m in s (fun (k, v) -> m := update k (combine k v) !m); !m let of_iter s = add_iter empty s let of_iter_with ~f s = add_iter_with ~f empty s let to_iter m yield = iter (fun k v -> yield (k, v)) m let keys m yield = iter (fun k _ -> yield k) m let values m yield = iter (fun _ v -> yield v) m let add_list m l = List.fold_left (fun m (k, v) -> add k v m) m l let add_list_with ~f m l = let combine k v = function | None -> Some v | Some v0 -> Some (f k v v0) in List.fold_left (fun m (k, v) -> update k (combine k v) m) m l let of_list l = add_list empty l let of_list_with ~f l = add_list_with ~f empty l let to_list m = fold (fun k v acc -> (k, v) :: acc) m [] let pp ?(pp_start = fun _ () -> ()) ?(pp_stop = fun _ () -> ()) ?(pp_arrow = fun fmt () -> Format.fprintf fmt "@ -> ") ?(pp_sep = fun fmt () -> Format.fprintf fmt ",@ ") pp_k pp_v fmt m = pp_start fmt (); let first = ref true in iter (fun k v -> if !first then first := false else pp_sep fmt (); pp_k fmt k; pp_arrow fmt (); pp_v fmt v) m; pp_stop fmt () end
a0b80ce6f4b66f272a6b3e859ff18378d5fc6a8707dc31ee5e7129dc6539e4a1
chef/chef-server
chef_index_tests.erl
Copyright 2015 Chef Server , Inc. All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% -module(chef_index_tests). -include_lib("eunit/include/eunit.hrl"). -define(EXPECTED_DOC, [<<"<doc>">>, [[<<"<field name=\"">>,<<"X_CHEF_id_CHEF_X">>,<<"\">">>,<<"a1">>, <<"</field>">>], [<<"<field name=\"">>,<<"X_CHEF_database_CHEF_X">>,<<"\">">>,<<"chef_db1">>, <<"</field>">>], [<<"<field name=\"">>,<<"X_CHEF_type_CHEF_X">>,<<"\">">>,<<"role">>, <<"</field>">>]], [], [<<"<field name=\"">>,<<"content">>,<<"\">">>, [[<<"X_CHEF_database_CHEF_X">>,<<"__=__">>,<<"chef_db1">>,<<" ">>], [<<"X_CHEF_id_CHEF_X">>,<<"__=__">>,<<"a1">>,<<" ">>], [<<"X_CHEF_type_CHEF_X">>,<<"__=__">>,<<"role">>,<<" ">>], [<<"key1">>,<<"__=__">>,<<"value1">>,<<" ">>], [<<"key2">>,<<"__=__">>,<<"value2">>,<<" ">>]], <<"</field>">>], <<"</doc>">>]). -define(EXPECTED_DELETE_DOC, [<<"<delete><id>">>,<<"a1">>,<<"</id></delete>">>]). chef_index_test_() -> Item = {[{<<"key1">>, <<"value1">>}, {<<"key2">>, <<"value2">>}]}, {foreach, fun() -> chef_index_test_utils:start_stats_hero(), application:ensure_all_started(prometheus), chef_index_expand:declare_metrics(), meck:new([chef_index_expand, chef_index_batch], [passthrough]) end, fun(_) -> meck:unload([chef_index_expand, chef_index_batch]) end, [{"add calls chef_index_batch:add_item when search_queue_mode is batch", fun() -> application:set_env(chef_index, search_queue_mode, batch), meck:expect(chef_index_batch, add_item, fun(?EXPECTED_DOC) -> ok end), chef_index:add(role, <<"a1">>, <<"db1">>, Item, <<"undefined">>), ?assert(meck:validate(chef_index_batch)) end }, {"add calls chef_index_expand:send_item when search_queue_mode is inline", fun() -> application:set_env(chef_index, search_queue_mode, inline), meck:expect(chef_index_expand, send_item, fun(?EXPECTED_DOC) -> ok end), chef_index:add(role, <<"a1">>, <<"db1">>, Item, <<"undefined">>), ?assert(meck:validate(chef_index_expand)) end }, {"add_batch adds each item passed to it", fun() -> application:set_env(chef_index, search_queue_mode, inline), meck:expect(chef_index_expand, send_item, fun(?EXPECTED_DOC) -> ok end), chef_index:add_batch([{role, <<"a1">>, <<"db1">>, Item}, {role, <<"a1">>, <<"db1">>, Item}, {role, <<"a1">>, <<"db1">>, Item}]), ?assertEqual(3, meck:num_calls(chef_index_expand, send_item, '_')) end }, {"delete calls chef_index_expand:send_delete when search_queue_mode is inline", fun() -> application:set_env(chef_index, search_queue_mode, inline), delete_assertion() end }, {"delete calls chef_index_expand:send_delete when search_queue_mode is batch", fun() -> application:set_env(chef_index, search_queue_mode, batch), delete_assertion() end} ] }. delete_assertion() -> meck:expect(chef_index_expand, send_delete, fun(?EXPECTED_DELETE_DOC) -> ok end), chef_index:delete(role, <<"a1">>, <<"db1">>, <<"abcd">>), ?assert(meck:validate(chef_index_expand)).
null
https://raw.githubusercontent.com/chef/chef-server/6d31841ecd73d984d819244add7ad6ebac284323/src/oc_erchef/apps/chef_index/test/chef_index_tests.erl
erlang
Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright 2015 Chef Server , Inc. All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(chef_index_tests). -include_lib("eunit/include/eunit.hrl"). -define(EXPECTED_DOC, [<<"<doc>">>, [[<<"<field name=\"">>,<<"X_CHEF_id_CHEF_X">>,<<"\">">>,<<"a1">>, <<"</field>">>], [<<"<field name=\"">>,<<"X_CHEF_database_CHEF_X">>,<<"\">">>,<<"chef_db1">>, <<"</field>">>], [<<"<field name=\"">>,<<"X_CHEF_type_CHEF_X">>,<<"\">">>,<<"role">>, <<"</field>">>]], [], [<<"<field name=\"">>,<<"content">>,<<"\">">>, [[<<"X_CHEF_database_CHEF_X">>,<<"__=__">>,<<"chef_db1">>,<<" ">>], [<<"X_CHEF_id_CHEF_X">>,<<"__=__">>,<<"a1">>,<<" ">>], [<<"X_CHEF_type_CHEF_X">>,<<"__=__">>,<<"role">>,<<" ">>], [<<"key1">>,<<"__=__">>,<<"value1">>,<<" ">>], [<<"key2">>,<<"__=__">>,<<"value2">>,<<" ">>]], <<"</field>">>], <<"</doc>">>]). -define(EXPECTED_DELETE_DOC, [<<"<delete><id>">>,<<"a1">>,<<"</id></delete>">>]). chef_index_test_() -> Item = {[{<<"key1">>, <<"value1">>}, {<<"key2">>, <<"value2">>}]}, {foreach, fun() -> chef_index_test_utils:start_stats_hero(), application:ensure_all_started(prometheus), chef_index_expand:declare_metrics(), meck:new([chef_index_expand, chef_index_batch], [passthrough]) end, fun(_) -> meck:unload([chef_index_expand, chef_index_batch]) end, [{"add calls chef_index_batch:add_item when search_queue_mode is batch", fun() -> application:set_env(chef_index, search_queue_mode, batch), meck:expect(chef_index_batch, add_item, fun(?EXPECTED_DOC) -> ok end), chef_index:add(role, <<"a1">>, <<"db1">>, Item, <<"undefined">>), ?assert(meck:validate(chef_index_batch)) end }, {"add calls chef_index_expand:send_item when search_queue_mode is inline", fun() -> application:set_env(chef_index, search_queue_mode, inline), meck:expect(chef_index_expand, send_item, fun(?EXPECTED_DOC) -> ok end), chef_index:add(role, <<"a1">>, <<"db1">>, Item, <<"undefined">>), ?assert(meck:validate(chef_index_expand)) end }, {"add_batch adds each item passed to it", fun() -> application:set_env(chef_index, search_queue_mode, inline), meck:expect(chef_index_expand, send_item, fun(?EXPECTED_DOC) -> ok end), chef_index:add_batch([{role, <<"a1">>, <<"db1">>, Item}, {role, <<"a1">>, <<"db1">>, Item}, {role, <<"a1">>, <<"db1">>, Item}]), ?assertEqual(3, meck:num_calls(chef_index_expand, send_item, '_')) end }, {"delete calls chef_index_expand:send_delete when search_queue_mode is inline", fun() -> application:set_env(chef_index, search_queue_mode, inline), delete_assertion() end }, {"delete calls chef_index_expand:send_delete when search_queue_mode is batch", fun() -> application:set_env(chef_index, search_queue_mode, batch), delete_assertion() end} ] }. delete_assertion() -> meck:expect(chef_index_expand, send_delete, fun(?EXPECTED_DELETE_DOC) -> ok end), chef_index:delete(role, <<"a1">>, <<"db1">>, <<"abcd">>), ?assert(meck:validate(chef_index_expand)).
1da35132a4eaac302fcb5828822dc1c9118a51e22625783cc1bc901927a4d8f0
jaked/orpc
orpc_pp.ml
* This file is part of orpc , OCaml signature to ONC RPC generator * Copyright ( C ) 2008 - 9 Skydeck , Inc * Copyright ( C ) 2010 * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details . * * You should have received a copy of the GNU Library 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 * This file is part of orpc, OCaml signature to ONC RPC generator * Copyright (C) 2008-9 Skydeck, Inc * Copyright (C) 2010 Jacob Donham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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 *) let pp_array pp'a fmt v = Format.fprintf fmt "@[<hv 3>[| %a |]@]" (fun fmt v -> let len = Array.length v in for i = 0 to len - 1 do pp'a fmt v.(i); if i < len - 1 then Format.fprintf fmt ";@ " done) v let pp_list pp'a fmt v = Format.fprintf fmt "@[<hv 2>[ %a ]@]" (fun fmt v -> let rec loop v = match v with | [] -> () | [v] -> pp'a fmt v | v::vs -> Format.fprintf fmt "%a;@ " pp'a v; loop vs in loop v) v let pp_option pp'a fmt v = match v with | None -> Format.fprintf fmt "None" | Some v -> Format.fprintf fmt "@[<hv 1>(Some@ %a)@]" pp'a v module type Trace = sig type t val trace_call : string -> (Format.formatter -> unit) -> t val trace_reply_ok : t -> (Format.formatter -> unit) -> unit val trace_reply_exn : t -> exn -> (Format.formatter -> unit) -> unit end module Trace_of_formatter (F : sig val formatter : Format.formatter end) : Trace = struct type t = unit let trace_call _ f = f F.formatter let trace_reply_ok _ f = f F.formatter let trace_reply_exn _ _ f = f F.formatter end
null
https://raw.githubusercontent.com/jaked/orpc/ecb5df8ec928070cd89cf035167fcedf3623ee3c/src/orpc/orpc_pp.ml
ocaml
* This file is part of orpc , OCaml signature to ONC RPC generator * Copyright ( C ) 2008 - 9 Skydeck , Inc * Copyright ( C ) 2010 * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details . * * You should have received a copy of the GNU Library 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 * This file is part of orpc, OCaml signature to ONC RPC generator * Copyright (C) 2008-9 Skydeck, Inc * Copyright (C) 2010 Jacob Donham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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 *) let pp_array pp'a fmt v = Format.fprintf fmt "@[<hv 3>[| %a |]@]" (fun fmt v -> let len = Array.length v in for i = 0 to len - 1 do pp'a fmt v.(i); if i < len - 1 then Format.fprintf fmt ";@ " done) v let pp_list pp'a fmt v = Format.fprintf fmt "@[<hv 2>[ %a ]@]" (fun fmt v -> let rec loop v = match v with | [] -> () | [v] -> pp'a fmt v | v::vs -> Format.fprintf fmt "%a;@ " pp'a v; loop vs in loop v) v let pp_option pp'a fmt v = match v with | None -> Format.fprintf fmt "None" | Some v -> Format.fprintf fmt "@[<hv 1>(Some@ %a)@]" pp'a v module type Trace = sig type t val trace_call : string -> (Format.formatter -> unit) -> t val trace_reply_ok : t -> (Format.formatter -> unit) -> unit val trace_reply_exn : t -> exn -> (Format.formatter -> unit) -> unit end module Trace_of_formatter (F : sig val formatter : Format.formatter end) : Trace = struct type t = unit let trace_call _ f = f F.formatter let trace_reply_ok _ f = f F.formatter let trace_reply_exn _ _ f = f F.formatter end
741690ff4bc355fc3020f9ab974696d7e0e2df94f6b250a3275f570881a3ee8d
avsm/eeww
odoc_to_text.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , 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 GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Text generation. This module contains the class [to_text] with methods used to transform information about elements to a [text] structure.*) open Odoc_info open Exception open Type open Value open Module open Class (** A class used to get a [text] for info structures. *) class virtual info = object (self) (** The list of pairs [(tag, f)] where [f] is a function taking the [text] associated to [tag] and returning a [text]. Add a pair here to handle a tag.*) val mutable tag_functions = ([] : (string * (Odoc_info.text -> Odoc_info.text)) list) (** @return [text] value for an authors list. *) method text_of_author_list l = match l with [] -> [] | _ -> [ Bold [Raw (Odoc_messages.authors^": ")] ; Raw (String.concat ", " l) ; Newline ] (** @return [text] value for the given optional version information.*) method text_of_version_opt v_opt = match v_opt with None -> [] | Some v -> [ Bold [Raw (Odoc_messages.version^": ")] ; Raw v ; Newline ] (** @return [text] value for the given optional since information.*) method text_of_since_opt s_opt = match s_opt with None -> [] | Some s -> [ Bold [Raw (Odoc_messages.since^": ")] ; Raw s ; Newline ] (** @return [text] value to represent the list of "before" information. *) method text_of_before = function [] -> [] | l -> let f (v, text) = (Bold [Raw (Printf.sprintf "%s %s " Odoc_messages.before v) ]) :: text @ [Newline] in List.flatten (List.map f l) (** @return [text] value for the given list of raised exceptions.*) method text_of_raised_exceptions l = match l with [] -> [] | (s, t) :: [] -> [ Bold [ Raw Odoc_messages.raises ] ; Raw " " ; Code s ; Raw " " ] @ t @ [ Newline ] | _ -> [ Bold [ Raw Odoc_messages.raises ] ; Raw " " ; List (List.map (fun (ex, desc) ->(Code ex) :: (Raw " ") :: desc ) l ) ; Newline ] (** Return [text] value for the given "see also" reference. *) method text_of_see (see_ref, t) = match see_ref with Odoc_info.See_url s -> [ Odoc_info.Link (s, t) ] | Odoc_info.See_file s -> (Odoc_info.Code s) :: (Odoc_info.Raw " ") :: t | Odoc_info.See_doc s -> (Odoc_info.Italic [Odoc_info.Raw s]) :: (Odoc_info.Raw " ") :: t (** Return [text] value for the given list of "see also" references.*) method text_of_sees l = match l with [] -> [] | see :: [] -> (Bold [ Raw Odoc_messages.see_also ]) :: (Raw " ") :: (self#text_of_see see) @ [ Newline ] | _ -> (Bold [ Raw Odoc_messages.see_also ]) :: [ List (List.map (fun see -> self#text_of_see see) l ); Newline ] (** @return [text] value for the given optional return information.*) method text_of_return_opt return_opt = match return_opt with None -> [] | Some t -> (Bold [Raw (Odoc_messages.returns^" ")]) :: t @ [ Newline ] (** Return a [text] for the given list of custom tagged texts. *) method text_of_custom l = List.fold_left (fun acc -> fun (tag, text) -> try let f = List.assoc tag tag_functions in match acc with [] -> f text | _ -> acc @ (Newline :: (f text)) with Not_found -> Odoc_info.warning (Odoc_messages.tag_not_handled tag) ; acc ) [] l method text_of_alerts alerts = List.concat_map (fun al -> let payload = match al.alert_payload with | Some p -> [ Raw ". "; Raw p ] | None -> [] in [ Bold [ Raw Odoc_messages.alert; Raw " "; Raw al.alert_name ] ] @ payload @ [ Newline ] ) alerts (** @return [text] value for a description, except for the i_params field. *) method text_of_info ?(block=true) info_opt = match info_opt with None -> [] | Some info -> let t = (match info.i_deprecated with None -> [] | Some t -> ( Italic [Raw (Odoc_messages.deprecated^". ")] ) :: t ) @ (match info.i_desc with None -> [] | Some t when t = [Odoc_info.Raw ""] -> [] | Some t -> t @ [ Newline ] ) @ (self#text_of_author_list info.i_authors) @ (self#text_of_version_opt info.i_version) @ (self#text_of_before info.i_before) @ (self#text_of_since_opt info.i_since) @ (self#text_of_raised_exceptions info.i_raised_exceptions) @ (self#text_of_return_opt info.i_return_value) @ (self#text_of_sees info.i_sees) @ (self#text_of_alerts info.i_alerts) @ (self#text_of_custom info.i_custom) in if block then [Block t] else t end (** This class defines methods to generate a [text] structure from elements. *) class virtual to_text = object (self) inherit info method virtual label : ?no_: bool -> string -> string (** Take a string and return the string where fully qualified idents have been replaced by idents relative to the given module name. Also remove the "hidden modules".*) method relative_idents m_name s = let f str_t = let match_s = Str.matched_string str_t in let rel = Name.get_relative m_name match_s in Odoc_info.apply_if_equal Odoc_info.use_hidden_modules match_s rel in Str.global_substitute (Str.regexp "\\([A-Z]\\([a-zA-Z_'0-9]\\)*\\.\\)+\\([a-z][a-zA-Z_'0-9]*\\)") f s (** Take a string and return the string where fully qualified idents have been replaced by idents relative to the given module name. Also remove the "hidden modules".*) method relative_module_idents m_name s = let f str_t = let match_s = Str.matched_string str_t in let rel = Name.get_relative m_name match_s in Odoc_info.apply_if_equal Odoc_info.use_hidden_modules match_s rel in Str.global_substitute (Str.regexp "\\([A-Z]\\([a-zA-Z_'0-9]\\)*\\.\\)+\\([A-Z][a-zA-Z_'0-9]*\\)") f s (** Get a string for a [Types.class_type] where all idents are relative. *) method normal_class_type m_name t = self#relative_idents m_name (Odoc_info.string_of_class_type t) (** Get a string for a [Types.module_type] where all idents are relative. *) method normal_module_type ?code m_name t = self#relative_module_idents m_name (Odoc_info.string_of_module_type ?code t) (** Get a string for a type where all idents are relative. *) method normal_type m_name t = self#relative_idents m_name (Odoc_info.string_of_type_expr t) (** Get a string for a list of types where all idents are relative. *) method normal_type_list ?par m_name sep t = self#relative_idents m_name (Odoc_info.string_of_type_list ?par sep t) method normal_cstr_args ?par m_name = function | Cstr_tuple l -> self#normal_type_list ?par m_name " * " l | Cstr_record r -> self#relative_idents m_name (Odoc_str.string_of_record r) (** Get a string for a list of class or class type type parameters where all idents are relative. *) method normal_class_type_param_list m_name t = self#relative_idents m_name (Odoc_info.string_of_class_type_param_list t) (** Get a string for the parameters of a class (with arrows) where all idents are relative. *) method normal_class_params m_name c = let s = Odoc_info.string_of_class_params c in self#relative_idents m_name (Odoc_info.remove_ending_newline s) (** @return [text] value to represent a [Types.type_expr].*) method text_of_type_expr module_name t = List.flatten (List.map (fun s -> [Code s ; Newline ]) (Str.split (Str.regexp "\n") (self#normal_type module_name t)) ) (** Return [text] value for a given short [Types.type_expr].*) method text_of_short_type_expr module_name t = [ Code (self#normal_type module_name t) ] (** Return [text] value or the given list of [Types.type_expr], with the given separator. *) method text_of_type_expr_list module_name sep l = [ Code (self#normal_type_list module_name sep l) ] (** Return [text] value or the given list of [Types.type_expr], as type parameters of a class of class type. *) method text_of_class_type_param_expr_list module_name l = [ Code (self#normal_class_type_param_list module_name l) ] (** @return [text] value to represent parameters of a class (with arrows).*) method text_of_class_params module_name c = Odoc_info.text_concat [Newline] (List.map (fun s -> [Code s]) (Str.split (Str.regexp "\n") (self#normal_class_params module_name c)) ) (** @return [text] value to represent a [Types.module_type]. *) method text_of_module_type t = let s = String.concat "\n" (Str.split (Str.regexp "\n") (Odoc_info.string_of_module_type t)) in [ Code s ] (** @return [text] value for a value. *) method text_of_value v = let name = v.val_name in let s_name = Name.simple name in let s = Format.fprintf Format.str_formatter "@[<hov 2>val %s :@ %s" s_name (self#normal_type (Name.father v.val_name) v.val_type); Format.flush_str_formatter () in [ CodePre s ] @ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @ (self#text_of_info v.val_info) (** @return [text] value for a class attribute. *) method text_of_attribute a = let s_name = Name.simple a.att_value.val_name in let mod_name = Name.father a.att_value.val_name in let s = Format.fprintf Format.str_formatter "@[<hov 2>val %s%s%s :@ %s" (if a.att_virtual then "virtual " else "") (if a.att_mutable then "mutable " else "") s_name (self#normal_type mod_name a.att_value.val_type); Format.flush_str_formatter () in (CodePre s) :: [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @ (self#text_of_info a.att_value.val_info) (** @return [text] value for a class method. *) method text_of_method m = let s_name = Name.simple m.met_value.val_name in let mod_name = Name.father m.met_value.val_name in let s = Format.fprintf Format.str_formatter "@[<hov 2>method %s%s%s :@ %s" (if m.met_private then "private " else "") (if m.met_virtual then "virtual " else "") s_name (self#normal_type mod_name m.met_value.val_type); Format.flush_str_formatter () in (CodePre s) :: [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @ (self#text_of_info m.met_value.val_info) (** @return [text] value for an exception. *) method text_of_exception e = let s_name = Name.simple e.ex_name in let father = Name.father e.ex_name in Format.fprintf Format.str_formatter "@[<hov 2>exception %s" s_name ; (match e.ex_args, e.ex_ret with Cstr_tuple [], None -> () | Cstr_tuple [], Some r -> Format.fprintf Format.str_formatter " %s@ %s" ":" (self#normal_type father r) | args, None -> Format.fprintf Format.str_formatter " %s@ %s" "of" (self#normal_cstr_args ~par:false father args) | args, Some r -> Format.fprintf Format.str_formatter " %s@ %s@ %s@ %s" ":" (self#normal_cstr_args ~par:false father args) "->" (self#normal_type father r) ); (match e.ex_alias with None -> () | Some ea -> Format.fprintf Format.str_formatter " = %s" ( match ea.ea_ex with None -> ea.ea_name | Some e -> e.ex_name ) ); let s2 = Format.flush_str_formatter () in [ CodePre s2 ] @ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @ (self#text_of_info e.ex_info) (** Return [text] value for the description of a function parameter. *) method text_of_parameter_description p = match Parameter.names p with [] -> [] | name :: [] -> ( Only one name , no need for label for the description . match Parameter.desc_by_name p name with None -> [] | Some t -> t ) | l -> (* A list of names, we display those with a description. *) let l2 = List.filter (fun n -> (Parameter.desc_by_name p n) <> None) l in match l2 with [] -> [] | _ -> [List (List.map (fun n -> match Parameter.desc_by_name p n with None -> [] (* should not occur *) | Some t -> [Code (n^" ") ; Raw ": "] @ t ) l2 ) ] (** Return [text] value for a list of parameters. *) method text_of_parameter_list m_name l = match l with [] -> [] | _ -> [ Bold [Raw Odoc_messages.parameters] ; Raw ":" ; List (List.map (fun p -> (match Parameter.complete_name p with "" -> Code "?" | s -> Code s ) :: [Code " : "] @ (self#text_of_short_type_expr m_name (Parameter.typ p)) @ [Newline] @ (self#text_of_parameter_description p) ) l ) ] (** Return [text] value for a list of module parameters. *) method text_of_module_parameter_list l = match l with [] -> [] | _ -> [ Newline ; Bold [Raw Odoc_messages.parameters] ; Raw ":" ; List (List.map (fun (p, desc_opt) -> begin match p.mp_type with None -> [Raw ""] | Some mty -> [Code (p.mp_name^" : ")] @ (self#text_of_module_type mty) end @ (match desc_opt with None -> [] | Some t -> (Raw " ") :: t) ) l ) ] (**/**) (** Return [text] value for the given [class_kind].*) method text_of_class_kind father ckind = match ckind with Class_structure _ -> [Code Odoc_messages.object_end] | Class_apply capp -> [Code ( ( match capp.capp_class with None -> capp.capp_name | Some cl -> cl.cl_name )^ " "^ (String.concat " " (List.map (fun s -> "("^s^")") capp.capp_params_code)) ) ] | Class_constr cco -> ( match cco.cco_type_parameters with [] -> [] | l -> (Code "["):: (self#text_of_type_expr_list father ", " l)@ [Code "] "] )@ [Code ( match cco.cco_class with None -> cco.cco_name | Some (Cl cl) -> Name.get_relative father cl.cl_name | Some (Cltype (clt,_)) -> Name.get_relative father clt.clt_name ) ] | Class_constraint (ck, ctk) -> [Code "( "] @ (self#text_of_class_kind father ck) @ [Code " : "] @ (self#text_of_class_type_kind father ctk) @ [Code " )"] (** Return [text] value for the given [class_type_kind].*) method text_of_class_type_kind father ctkind = match ctkind with Class_type cta -> ( match cta.cta_type_parameters with [] -> [] | l -> (Code "[") :: (self#text_of_class_type_param_expr_list father l) @ [Code "] "] ) @ ( match cta.cta_class with None -> [ Code cta.cta_name ] | Some (Cltype (clt, _)) -> let rel = Name.get_relative father clt.clt_name in [Code rel] | Some (Cl cl) -> let rel = Name.get_relative father cl.cl_name in [Code rel] ) | Class_signature _ -> [Code Odoc_messages.object_end] (** Return [text] value for a [module_kind]. *) method text_of_module_kind ?(with_def_syntax=true) k = match k with Module_alias m_alias -> (match m_alias.ma_module with None -> [Code ((if with_def_syntax then " = " else "")^m_alias.ma_name)] | Some (Mod m) -> [Code ((if with_def_syntax then " = " else "")^m.m_name)] | Some (Modtype mt) -> [Code ((if with_def_syntax then " = " else "")^mt.mt_name)] ) | Module_apply (k1, k2) -> (if with_def_syntax then [Code " = "] else []) @ (self#text_of_module_kind ~with_def_syntax: false k1) @ [Code " ( "] @ (self#text_of_module_kind ~with_def_syntax: false k2) @ [Code " ) "] | Module_with (tk, code) -> (if with_def_syntax then [Code " : "] else []) @ (self#text_of_module_type_kind ~with_def_syntax: false tk) @ [Code code] | Module_constraint (k, tk) -> (if with_def_syntax then [Code " : "] else []) @ [Code "( "] @ (self#text_of_module_kind ~with_def_syntax: false k) @ [Code " : "] @ (self#text_of_module_type_kind ~with_def_syntax: false tk) @ [Code " )"] | Module_struct _ -> [Code ((if with_def_syntax then " : " else "")^ Odoc_messages.struct_end^" ")] | Module_functor (_, k) -> (if with_def_syntax then [Code " : "] else []) @ [Code "functor ... "] @ [Code " -> "] @ (self#text_of_module_kind ~with_def_syntax: false k) | Module_typeof s -> let code = Printf.sprintf "%smodule type of %s" (if with_def_syntax then " : " else "") s in [Code code] | Module_unpack (code, _) -> let code = Printf.sprintf "%s%s" (if with_def_syntax then " : " else "") code in [Code code] (** Return html code for a [module_type_kind].*) method text_of_module_type_kind ?(with_def_syntax=true) tk = match tk with | Module_type_struct _ -> [Code ((if with_def_syntax then " = " else "")^Odoc_messages.sig_end)] | Module_type_functor (p, k) -> let t1 = [Code ("("^p.mp_name^" : ")] @ (self#text_of_module_type_kind p.mp_kind) @ [Code ") -> "] in let t2 = self#text_of_module_type_kind ~with_def_syntax: false k in (if with_def_syntax then [Code " = "] else []) @ t1 @ t2 | Module_type_with (tk2, code) -> let t = self#text_of_module_type_kind ~with_def_syntax: false tk2 in (if with_def_syntax then [Code " = "] else []) @ t @ [Code code] | Module_type_alias mt_alias -> [Code ((if with_def_syntax then " = " else "")^ (match mt_alias.mta_module with None -> mt_alias.mta_name | Some mt -> mt.mt_name)) ] | Odoc_module.Module_type_typeof s -> let code = Printf.sprintf "%smodule type of %s" (if with_def_syntax then " = " else "") s in [ Code code ] end
null
https://raw.githubusercontent.com/avsm/eeww/4834abb9a40a9f35d0d7041a61e53e3426d8886f/boot/ocaml/ocamldoc/odoc_to_text.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Text generation. This module contains the class [to_text] with methods used to transform information about elements to a [text] structure. * A class used to get a [text] for info structures. * The list of pairs [(tag, f)] where [f] is a function taking the [text] associated to [tag] and returning a [text]. Add a pair here to handle a tag. * @return [text] value for an authors list. * @return [text] value for the given optional version information. * @return [text] value for the given optional since information. * @return [text] value to represent the list of "before" information. * @return [text] value for the given list of raised exceptions. * Return [text] value for the given "see also" reference. * Return [text] value for the given list of "see also" references. * @return [text] value for the given optional return information. * Return a [text] for the given list of custom tagged texts. * @return [text] value for a description, except for the i_params field. * This class defines methods to generate a [text] structure from elements. * Take a string and return the string where fully qualified idents have been replaced by idents relative to the given module name. Also remove the "hidden modules". * Take a string and return the string where fully qualified idents have been replaced by idents relative to the given module name. Also remove the "hidden modules". * Get a string for a [Types.class_type] where all idents are relative. * Get a string for a [Types.module_type] where all idents are relative. * Get a string for a type where all idents are relative. * Get a string for a list of types where all idents are relative. * Get a string for a list of class or class type type parameters where all idents are relative. * Get a string for the parameters of a class (with arrows) where all idents are relative. * @return [text] value to represent a [Types.type_expr]. * Return [text] value for a given short [Types.type_expr]. * Return [text] value or the given list of [Types.type_expr], with the given separator. * Return [text] value or the given list of [Types.type_expr], as type parameters of a class of class type. * @return [text] value to represent parameters of a class (with arrows). * @return [text] value to represent a [Types.module_type]. * @return [text] value for a value. * @return [text] value for a class attribute. * @return [text] value for a class method. * @return [text] value for an exception. * Return [text] value for the description of a function parameter. A list of names, we display those with a description. should not occur * Return [text] value for a list of parameters. * Return [text] value for a list of module parameters. */* * Return [text] value for the given [class_kind]. * Return [text] value for the given [class_type_kind]. * Return [text] value for a [module_kind]. * Return html code for a [module_type_kind].
, projet Cristal , INRIA Rocquencourt Copyright 2001 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Odoc_info open Exception open Type open Value open Module open Class class virtual info = object (self) val mutable tag_functions = ([] : (string * (Odoc_info.text -> Odoc_info.text)) list) method text_of_author_list l = match l with [] -> [] | _ -> [ Bold [Raw (Odoc_messages.authors^": ")] ; Raw (String.concat ", " l) ; Newline ] method text_of_version_opt v_opt = match v_opt with None -> [] | Some v -> [ Bold [Raw (Odoc_messages.version^": ")] ; Raw v ; Newline ] method text_of_since_opt s_opt = match s_opt with None -> [] | Some s -> [ Bold [Raw (Odoc_messages.since^": ")] ; Raw s ; Newline ] method text_of_before = function [] -> [] | l -> let f (v, text) = (Bold [Raw (Printf.sprintf "%s %s " Odoc_messages.before v) ]) :: text @ [Newline] in List.flatten (List.map f l) method text_of_raised_exceptions l = match l with [] -> [] | (s, t) :: [] -> [ Bold [ Raw Odoc_messages.raises ] ; Raw " " ; Code s ; Raw " " ] @ t @ [ Newline ] | _ -> [ Bold [ Raw Odoc_messages.raises ] ; Raw " " ; List (List.map (fun (ex, desc) ->(Code ex) :: (Raw " ") :: desc ) l ) ; Newline ] method text_of_see (see_ref, t) = match see_ref with Odoc_info.See_url s -> [ Odoc_info.Link (s, t) ] | Odoc_info.See_file s -> (Odoc_info.Code s) :: (Odoc_info.Raw " ") :: t | Odoc_info.See_doc s -> (Odoc_info.Italic [Odoc_info.Raw s]) :: (Odoc_info.Raw " ") :: t method text_of_sees l = match l with [] -> [] | see :: [] -> (Bold [ Raw Odoc_messages.see_also ]) :: (Raw " ") :: (self#text_of_see see) @ [ Newline ] | _ -> (Bold [ Raw Odoc_messages.see_also ]) :: [ List (List.map (fun see -> self#text_of_see see) l ); Newline ] method text_of_return_opt return_opt = match return_opt with None -> [] | Some t -> (Bold [Raw (Odoc_messages.returns^" ")]) :: t @ [ Newline ] method text_of_custom l = List.fold_left (fun acc -> fun (tag, text) -> try let f = List.assoc tag tag_functions in match acc with [] -> f text | _ -> acc @ (Newline :: (f text)) with Not_found -> Odoc_info.warning (Odoc_messages.tag_not_handled tag) ; acc ) [] l method text_of_alerts alerts = List.concat_map (fun al -> let payload = match al.alert_payload with | Some p -> [ Raw ". "; Raw p ] | None -> [] in [ Bold [ Raw Odoc_messages.alert; Raw " "; Raw al.alert_name ] ] @ payload @ [ Newline ] ) alerts method text_of_info ?(block=true) info_opt = match info_opt with None -> [] | Some info -> let t = (match info.i_deprecated with None -> [] | Some t -> ( Italic [Raw (Odoc_messages.deprecated^". ")] ) :: t ) @ (match info.i_desc with None -> [] | Some t when t = [Odoc_info.Raw ""] -> [] | Some t -> t @ [ Newline ] ) @ (self#text_of_author_list info.i_authors) @ (self#text_of_version_opt info.i_version) @ (self#text_of_before info.i_before) @ (self#text_of_since_opt info.i_since) @ (self#text_of_raised_exceptions info.i_raised_exceptions) @ (self#text_of_return_opt info.i_return_value) @ (self#text_of_sees info.i_sees) @ (self#text_of_alerts info.i_alerts) @ (self#text_of_custom info.i_custom) in if block then [Block t] else t end class virtual to_text = object (self) inherit info method virtual label : ?no_: bool -> string -> string method relative_idents m_name s = let f str_t = let match_s = Str.matched_string str_t in let rel = Name.get_relative m_name match_s in Odoc_info.apply_if_equal Odoc_info.use_hidden_modules match_s rel in Str.global_substitute (Str.regexp "\\([A-Z]\\([a-zA-Z_'0-9]\\)*\\.\\)+\\([a-z][a-zA-Z_'0-9]*\\)") f s method relative_module_idents m_name s = let f str_t = let match_s = Str.matched_string str_t in let rel = Name.get_relative m_name match_s in Odoc_info.apply_if_equal Odoc_info.use_hidden_modules match_s rel in Str.global_substitute (Str.regexp "\\([A-Z]\\([a-zA-Z_'0-9]\\)*\\.\\)+\\([A-Z][a-zA-Z_'0-9]*\\)") f s method normal_class_type m_name t = self#relative_idents m_name (Odoc_info.string_of_class_type t) method normal_module_type ?code m_name t = self#relative_module_idents m_name (Odoc_info.string_of_module_type ?code t) method normal_type m_name t = self#relative_idents m_name (Odoc_info.string_of_type_expr t) method normal_type_list ?par m_name sep t = self#relative_idents m_name (Odoc_info.string_of_type_list ?par sep t) method normal_cstr_args ?par m_name = function | Cstr_tuple l -> self#normal_type_list ?par m_name " * " l | Cstr_record r -> self#relative_idents m_name (Odoc_str.string_of_record r) method normal_class_type_param_list m_name t = self#relative_idents m_name (Odoc_info.string_of_class_type_param_list t) method normal_class_params m_name c = let s = Odoc_info.string_of_class_params c in self#relative_idents m_name (Odoc_info.remove_ending_newline s) method text_of_type_expr module_name t = List.flatten (List.map (fun s -> [Code s ; Newline ]) (Str.split (Str.regexp "\n") (self#normal_type module_name t)) ) method text_of_short_type_expr module_name t = [ Code (self#normal_type module_name t) ] method text_of_type_expr_list module_name sep l = [ Code (self#normal_type_list module_name sep l) ] method text_of_class_type_param_expr_list module_name l = [ Code (self#normal_class_type_param_list module_name l) ] method text_of_class_params module_name c = Odoc_info.text_concat [Newline] (List.map (fun s -> [Code s]) (Str.split (Str.regexp "\n") (self#normal_class_params module_name c)) ) method text_of_module_type t = let s = String.concat "\n" (Str.split (Str.regexp "\n") (Odoc_info.string_of_module_type t)) in [ Code s ] method text_of_value v = let name = v.val_name in let s_name = Name.simple name in let s = Format.fprintf Format.str_formatter "@[<hov 2>val %s :@ %s" s_name (self#normal_type (Name.father v.val_name) v.val_type); Format.flush_str_formatter () in [ CodePre s ] @ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @ (self#text_of_info v.val_info) method text_of_attribute a = let s_name = Name.simple a.att_value.val_name in let mod_name = Name.father a.att_value.val_name in let s = Format.fprintf Format.str_formatter "@[<hov 2>val %s%s%s :@ %s" (if a.att_virtual then "virtual " else "") (if a.att_mutable then "mutable " else "") s_name (self#normal_type mod_name a.att_value.val_type); Format.flush_str_formatter () in (CodePre s) :: [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @ (self#text_of_info a.att_value.val_info) method text_of_method m = let s_name = Name.simple m.met_value.val_name in let mod_name = Name.father m.met_value.val_name in let s = Format.fprintf Format.str_formatter "@[<hov 2>method %s%s%s :@ %s" (if m.met_private then "private " else "") (if m.met_virtual then "virtual " else "") s_name (self#normal_type mod_name m.met_value.val_type); Format.flush_str_formatter () in (CodePre s) :: [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @ (self#text_of_info m.met_value.val_info) method text_of_exception e = let s_name = Name.simple e.ex_name in let father = Name.father e.ex_name in Format.fprintf Format.str_formatter "@[<hov 2>exception %s" s_name ; (match e.ex_args, e.ex_ret with Cstr_tuple [], None -> () | Cstr_tuple [], Some r -> Format.fprintf Format.str_formatter " %s@ %s" ":" (self#normal_type father r) | args, None -> Format.fprintf Format.str_formatter " %s@ %s" "of" (self#normal_cstr_args ~par:false father args) | args, Some r -> Format.fprintf Format.str_formatter " %s@ %s@ %s@ %s" ":" (self#normal_cstr_args ~par:false father args) "->" (self#normal_type father r) ); (match e.ex_alias with None -> () | Some ea -> Format.fprintf Format.str_formatter " = %s" ( match ea.ea_ex with None -> ea.ea_name | Some e -> e.ex_name ) ); let s2 = Format.flush_str_formatter () in [ CodePre s2 ] @ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @ (self#text_of_info e.ex_info) method text_of_parameter_description p = match Parameter.names p with [] -> [] | name :: [] -> ( Only one name , no need for label for the description . match Parameter.desc_by_name p name with None -> [] | Some t -> t ) | l -> let l2 = List.filter (fun n -> (Parameter.desc_by_name p n) <> None) l in match l2 with [] -> [] | _ -> [List (List.map (fun n -> match Parameter.desc_by_name p n with | Some t -> [Code (n^" ") ; Raw ": "] @ t ) l2 ) ] method text_of_parameter_list m_name l = match l with [] -> [] | _ -> [ Bold [Raw Odoc_messages.parameters] ; Raw ":" ; List (List.map (fun p -> (match Parameter.complete_name p with "" -> Code "?" | s -> Code s ) :: [Code " : "] @ (self#text_of_short_type_expr m_name (Parameter.typ p)) @ [Newline] @ (self#text_of_parameter_description p) ) l ) ] method text_of_module_parameter_list l = match l with [] -> [] | _ -> [ Newline ; Bold [Raw Odoc_messages.parameters] ; Raw ":" ; List (List.map (fun (p, desc_opt) -> begin match p.mp_type with None -> [Raw ""] | Some mty -> [Code (p.mp_name^" : ")] @ (self#text_of_module_type mty) end @ (match desc_opt with None -> [] | Some t -> (Raw " ") :: t) ) l ) ] method text_of_class_kind father ckind = match ckind with Class_structure _ -> [Code Odoc_messages.object_end] | Class_apply capp -> [Code ( ( match capp.capp_class with None -> capp.capp_name | Some cl -> cl.cl_name )^ " "^ (String.concat " " (List.map (fun s -> "("^s^")") capp.capp_params_code)) ) ] | Class_constr cco -> ( match cco.cco_type_parameters with [] -> [] | l -> (Code "["):: (self#text_of_type_expr_list father ", " l)@ [Code "] "] )@ [Code ( match cco.cco_class with None -> cco.cco_name | Some (Cl cl) -> Name.get_relative father cl.cl_name | Some (Cltype (clt,_)) -> Name.get_relative father clt.clt_name ) ] | Class_constraint (ck, ctk) -> [Code "( "] @ (self#text_of_class_kind father ck) @ [Code " : "] @ (self#text_of_class_type_kind father ctk) @ [Code " )"] method text_of_class_type_kind father ctkind = match ctkind with Class_type cta -> ( match cta.cta_type_parameters with [] -> [] | l -> (Code "[") :: (self#text_of_class_type_param_expr_list father l) @ [Code "] "] ) @ ( match cta.cta_class with None -> [ Code cta.cta_name ] | Some (Cltype (clt, _)) -> let rel = Name.get_relative father clt.clt_name in [Code rel] | Some (Cl cl) -> let rel = Name.get_relative father cl.cl_name in [Code rel] ) | Class_signature _ -> [Code Odoc_messages.object_end] method text_of_module_kind ?(with_def_syntax=true) k = match k with Module_alias m_alias -> (match m_alias.ma_module with None -> [Code ((if with_def_syntax then " = " else "")^m_alias.ma_name)] | Some (Mod m) -> [Code ((if with_def_syntax then " = " else "")^m.m_name)] | Some (Modtype mt) -> [Code ((if with_def_syntax then " = " else "")^mt.mt_name)] ) | Module_apply (k1, k2) -> (if with_def_syntax then [Code " = "] else []) @ (self#text_of_module_kind ~with_def_syntax: false k1) @ [Code " ( "] @ (self#text_of_module_kind ~with_def_syntax: false k2) @ [Code " ) "] | Module_with (tk, code) -> (if with_def_syntax then [Code " : "] else []) @ (self#text_of_module_type_kind ~with_def_syntax: false tk) @ [Code code] | Module_constraint (k, tk) -> (if with_def_syntax then [Code " : "] else []) @ [Code "( "] @ (self#text_of_module_kind ~with_def_syntax: false k) @ [Code " : "] @ (self#text_of_module_type_kind ~with_def_syntax: false tk) @ [Code " )"] | Module_struct _ -> [Code ((if with_def_syntax then " : " else "")^ Odoc_messages.struct_end^" ")] | Module_functor (_, k) -> (if with_def_syntax then [Code " : "] else []) @ [Code "functor ... "] @ [Code " -> "] @ (self#text_of_module_kind ~with_def_syntax: false k) | Module_typeof s -> let code = Printf.sprintf "%smodule type of %s" (if with_def_syntax then " : " else "") s in [Code code] | Module_unpack (code, _) -> let code = Printf.sprintf "%s%s" (if with_def_syntax then " : " else "") code in [Code code] method text_of_module_type_kind ?(with_def_syntax=true) tk = match tk with | Module_type_struct _ -> [Code ((if with_def_syntax then " = " else "")^Odoc_messages.sig_end)] | Module_type_functor (p, k) -> let t1 = [Code ("("^p.mp_name^" : ")] @ (self#text_of_module_type_kind p.mp_kind) @ [Code ") -> "] in let t2 = self#text_of_module_type_kind ~with_def_syntax: false k in (if with_def_syntax then [Code " = "] else []) @ t1 @ t2 | Module_type_with (tk2, code) -> let t = self#text_of_module_type_kind ~with_def_syntax: false tk2 in (if with_def_syntax then [Code " = "] else []) @ t @ [Code code] | Module_type_alias mt_alias -> [Code ((if with_def_syntax then " = " else "")^ (match mt_alias.mta_module with None -> mt_alias.mta_name | Some mt -> mt.mt_name)) ] | Odoc_module.Module_type_typeof s -> let code = Printf.sprintf "%smodule type of %s" (if with_def_syntax then " = " else "") s in [ Code code ] end
44dc00470424d6d6cd081b55adc235e7e24953c441ce0be5fdd378d50e2a5910
bmeurer/ocaml-experimental
odoc_exception.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$ (** Representation and manipulation of exceptions. *) module Name = Odoc_name type exception_alias = { ea_name : Name.t ; mutable ea_ex : t_exception option ; } and t_exception = { ex_name : Name.t ; mutable ex_info : Odoc_types.info option ; (** optional user information *) ex_args : Types.type_expr list ; (** the types of the parameters *) ex_alias : exception_alias option ; mutable ex_loc : Odoc_types.location ; mutable ex_code : string option ; }
null
https://raw.githubusercontent.com/bmeurer/ocaml-experimental/fe5c10cdb0499e43af4b08f35a3248e5c1a8b541/ocamldoc/odoc_exception.ml
ocaml
********************************************************************* OCamldoc ********************************************************************* * Representation and manipulation of exceptions. * optional user information * the types of the parameters
, 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$ module Name = Odoc_name type exception_alias = { ea_name : Name.t ; mutable ea_ex : t_exception option ; } and t_exception = { ex_name : Name.t ; ex_alias : exception_alias option ; mutable ex_loc : Odoc_types.location ; mutable ex_code : string option ; }
259184278fa3ee44ab50a1051633574353601590f3eff6a049514dbd86e727e5
clj-easy/graalvm-clojure
main.clj
(ns simple.main (:require [next.jdbc :as jdbc] [clojure.string :as str] [honeysql.core :as sql] [honeysql.helpers :refer [select insert-into columns values from]]) (:gen-class)) (set! *warn-on-reflection* true) (def sql-create-table ["CREATE TABLE IF NOT EXISTS graalvm_test (id SERIAL PRIMARY KEY, name VARCHAR(10) NOT NULL, appearance VARCHAR(10) NOT NULL, cost INT NOT NULL)"]) (def sql-read-all ["SELECT * FROM graalvm_test"]) (def honey-sql-read-all (sql/format {:select [:*] :from [:graalvm_test]})) (def honey-sql-read-all-2 (sql/format (-> (select :*) (from :graalvm_test)))) (def sql-delete-table ["DELETE FROM graalvm_test"]) (def sql-insert-fruits ["INSERT INTO graalvm_test (name, appearance, cost) VALUES ('Apple', 'rosy', 509), ('Pear', 'pearish', 428), ('Orange', 'round', 724)"]) (def honey-sql-insert-fruits (-> (insert-into :graalvm_test) (columns :name :appearance :cost) (values [ ["Grape" "tiny" 1] ["Mango" "odd" 312] ["Pineapple" "spiky" 956]]) sql/format)) (defn -main [] (let [creds (slurp "./database.env") datasource (jdbc/get-datasource {:dbtype "postgresql" :dbname (second (re-find #"POSTGRES_DB=(.*)" creds)) :user (second (re-find #"POSTGRES_USER=(.*)" creds)) :password (second (re-find #"POSTGRES_PASSWORD=(.*)" creds)) :host "localhost" :port 5432 :useSSL false}) table-name "graalvm_test"] (with-open [connection (jdbc/get-connection datasource)] (println "create table" table-name) (jdbc/execute! connection sql-create-table) (println "inserting fruit into" table-name) (jdbc/execute! connection sql-insert-fruits) (jdbc/execute! connection honey-sql-insert-fruits) (println "read with next.jdbc:") (doseq [result (jdbc/execute! connection sql-read-all)] (println result)) (println "read with honey-sql:") (doseq [result (jdbc/execute! connection honey-sql-read-all)] (println result)) (println "read with honey-sql helpers:") (doseq [result (jdbc/execute! connection honey-sql-read-all-2)] (println result)) (jdbc/execute! connection sql-delete-table))) (println "Hello GraalVM."))
null
https://raw.githubusercontent.com/clj-easy/graalvm-clojure/5de155ad4f95d5dac97aac1ab3d118400e7d186f/next-jdbc/src/simple/main.clj
clojure
(ns simple.main (:require [next.jdbc :as jdbc] [clojure.string :as str] [honeysql.core :as sql] [honeysql.helpers :refer [select insert-into columns values from]]) (:gen-class)) (set! *warn-on-reflection* true) (def sql-create-table ["CREATE TABLE IF NOT EXISTS graalvm_test (id SERIAL PRIMARY KEY, name VARCHAR(10) NOT NULL, appearance VARCHAR(10) NOT NULL, cost INT NOT NULL)"]) (def sql-read-all ["SELECT * FROM graalvm_test"]) (def honey-sql-read-all (sql/format {:select [:*] :from [:graalvm_test]})) (def honey-sql-read-all-2 (sql/format (-> (select :*) (from :graalvm_test)))) (def sql-delete-table ["DELETE FROM graalvm_test"]) (def sql-insert-fruits ["INSERT INTO graalvm_test (name, appearance, cost) VALUES ('Apple', 'rosy', 509), ('Pear', 'pearish', 428), ('Orange', 'round', 724)"]) (def honey-sql-insert-fruits (-> (insert-into :graalvm_test) (columns :name :appearance :cost) (values [ ["Grape" "tiny" 1] ["Mango" "odd" 312] ["Pineapple" "spiky" 956]]) sql/format)) (defn -main [] (let [creds (slurp "./database.env") datasource (jdbc/get-datasource {:dbtype "postgresql" :dbname (second (re-find #"POSTGRES_DB=(.*)" creds)) :user (second (re-find #"POSTGRES_USER=(.*)" creds)) :password (second (re-find #"POSTGRES_PASSWORD=(.*)" creds)) :host "localhost" :port 5432 :useSSL false}) table-name "graalvm_test"] (with-open [connection (jdbc/get-connection datasource)] (println "create table" table-name) (jdbc/execute! connection sql-create-table) (println "inserting fruit into" table-name) (jdbc/execute! connection sql-insert-fruits) (jdbc/execute! connection honey-sql-insert-fruits) (println "read with next.jdbc:") (doseq [result (jdbc/execute! connection sql-read-all)] (println result)) (println "read with honey-sql:") (doseq [result (jdbc/execute! connection honey-sql-read-all)] (println result)) (println "read with honey-sql helpers:") (doseq [result (jdbc/execute! connection honey-sql-read-all-2)] (println result)) (jdbc/execute! connection sql-delete-table))) (println "Hello GraalVM."))
36be701dbf1f0988313f984cd2776fe95d83a1adb75f418f9e32c8add413c8f7
OCamlPro/operf-micro
almabench.ml
* ALMABENCH 1.0.1 * OCaml version * * A number - crunching benchmark designed for cross - language and vendor * comparisons . * * Written by , from versions for * C++ and java . * * No rights reserved . This is public domain software , for use by anyone . * * This program calculates the daily ephemeris ( at noon ) for the years * 2000 - 2099 using an algorithm developed by , , J. * , and of the Bureau des * Longitudes , Paris , France ) , as detailed in Astronomy & Astrophysics * 282 , 663 ( 1994 ) * * Note that the code herein is design for the purpose of testing * computational performance ; error handling and other such " niceties " * is virtually non - existent . * * Actual ( and oft - updated ) benchmark results can be found at : * * * Please do not use this information or algorithm in any way that might * upset the balance of the universe or otherwise cause planets to impact * upon one another . * ALMABENCH 1.0.1 * OCaml version * * A number-crunching benchmark designed for cross-language and vendor * comparisons. * * Written by Shawn Wagner, from Scott Robert Ladd's versions for * C++ and java. * * No rights reserved. This is public domain software, for use by anyone. * * This program calculates the daily ephemeris (at noon) for the years * 2000-2099 using an algorithm developed by J.L. Simon, P. Bretagnon, J. * Chapront, M. Chapront-Touze, G. Francou and J. Laskar of the Bureau des * Longitudes, Paris, France), as detailed in Astronomy & Astrophysics * 282, 663 (1994) * * Note that the code herein is design for the purpose of testing * computational performance; error handling and other such "niceties" * is virtually non-existent. * * Actual (and oft-updated) benchmark results can be found at: * * * Please do not use this information or algorithm in any way that might * upset the balance of the universe or otherwise cause planets to impact * upon one another. *) let pic = 3.14159265358979323846 and j2000 = 2451545.0 and jcentury = 36525.0 and jmillenia = 365250.0 let twopi = 2.0 *. pic and a2r = pic /. 648000.0 and r2h = 12.0 /. pic and r2d = 180.0 /. pic and gaussk = 0.01720209895 (* number of days to include in test *) let test_loops = 5 ( \ * was : 20 * \ ) and = 36525 sin and cos of j2000 mean obliquity ( iau 1976 ) and sineps = 0.3977771559319137 and coseps = 0.9174820620691818 and amas = [| 6023600.0; 408523.5; 328900.5; 3098710.0; 1047.355; 3498.5; 22869.0; 19314.0 |] * tables giving the mean keplerian elements , limited to t**2 terms : * a semi - major axis ( au ) * dlm mean longitude ( degree and arcsecond ) * e eccentricity * pi longitude of the perihelion ( degree and arcsecond ) * dinc inclination ( degree and arcsecond ) * omega longitude of the ascending node ( degree and arcsecond ) * tables giving the mean keplerian elements, limited to t**2 terms: * a semi-major axis (au) * dlm mean longitude (degree and arcsecond) * e eccentricity * pi longitude of the perihelion (degree and arcsecond) * dinc inclination (degree and arcsecond) * omega longitude of the ascending node (degree and arcsecond) *) and a = [| [| 0.3870983098; 0.0; 0.0 |]; [| 0.7233298200; 0.0; 0.0 |]; [| 1.0000010178; 0.0; 0.0 |]; [| 1.5236793419; 3e-10; 0.0 |]; [| 5.2026032092; 19132e-10; -39e-10 |]; [| 9.5549091915; -0.0000213896; 444e-10 |]; [| 19.2184460618; -3716e-10; 979e-10 |]; [| 30.1103868694; -16635e-10; 686e-10 |] |] and dlm = [| [| 252.25090552; 5381016286.88982; -1.92789 |]; [| 181.97980085; 2106641364.33548; 0.59381 |]; [| 100.46645683; 1295977422.83429; -2.04411 |]; [| 355.43299958; 689050774.93988; 0.94264 |]; [| 34.35151874; 109256603.77991; -30.60378 |]; [| 50.07744430; 43996098.55732; 75.61614 |]; [| 314.05500511; 15424811.93933; -1.75083 |]; [| 304.34866548; 7865503.20744; 0.21103 |] |] and e = [| [| 0.2056317526; 0.0002040653; -28349e-10 |]; [| 0.0067719164; -0.0004776521; 98127e-10 |]; [| 0.0167086342; -0.0004203654; -0.0000126734 |]; [| 0.0934006477; 0.0009048438; -80641e-10 |]; [| 0.0484979255; 0.0016322542; -0.0000471366 |]; [| 0.0555481426; -0.0034664062; -0.0000643639 |]; [| 0.0463812221; -0.0002729293; 0.0000078913 |]; [| 0.0094557470; 0.0000603263; 0.0 |] |] and pi = [| [| 77.45611904; 5719.11590; -4.83016 |]; [| 131.56370300; 175.48640; -498.48184 |]; [| 102.93734808; 11612.35290; 53.27577 |]; [| 336.06023395; 15980.45908; -62.32800 |]; [| 14.33120687; 7758.75163; 259.95938 |]; [| 93.05723748; 20395.49439; 190.25952 |]; [| 173.00529106; 3215.56238; -34.09288 |]; [| 48.12027554; 1050.71912; 27.39717 |] |] and dinc = [| [| 7.00498625; -214.25629; 0.28977 |]; [| 3.39466189; -30.84437; -11.67836 |]; [| 0.0; 469.97289; -3.35053 |]; [| 1.84972648; -293.31722; -8.11830 |]; [| 1.30326698; -71.55890; 11.95297 |]; [| 2.48887878; 91.85195; -17.66225 |]; [| 0.77319689; -60.72723; 1.25759 |]; [| 1.76995259; 8.12333; 0.08135 |] |] and omega = [| [| 48.33089304; -4515.21727; -31.79892 |]; [| 76.67992019; -10008.48154; -51.32614 |]; [| 174.87317577; -8679.27034; 15.34191 |]; [| 49.55809321; -10620.90088; -230.57416 |]; [| 100.46440702; 6362.03561; 326.52178 |]; [| 113.66550252; -9240.19942; -66.23743 |]; [| 74.00595701; 2669.15033; 145.93964 |]; [| 131.78405702; -221.94322; -0.78728 |] |] (* tables for trigonometric terms to be added to the mean elements of the semi-major axes. *) and kp = [| [| 69613.0; 75645.0; 88306.0; 59899.0; 15746.0; 71087.0; 142173.0; 3086.0; 0.0 |]; [| 21863.0; 32794.0; 26934.0; 10931.0; 26250.0; 43725.0; 53867.0; 28939.0; 0.0 |]; [| 16002.0; 21863.0; 32004.0; 10931.0; 14529.0; 16368.0; 15318.0; 32794.0; 0.0 |]; [| 6345.0; 7818.0; 15636.0; 7077.0; 8184.0; 14163.0; 1107.0; 4872.0; 0.0 |]; [| 1760.0; 1454.0; 1167.0; 880.0; 287.0; 2640.0; 19.0; 2047.0; 1454.0 |]; [| 574.0; 0.0; 880.0; 287.0; 19.0; 1760.0; 1167.0; 306.0; 574.0 |]; [| 204.0; 0.0; 177.0; 1265.0; 4.0; 385.0; 200.0; 208.0; 204.0 |]; [| 0.0; 102.0; 106.0; 4.0; 98.0; 1367.0; 487.0; 204.0; 0.0 |] |] and ca = [| [| 4.0; -13.0; 11.0; -9.0; -9.0; -3.0; -1.0; 4.0; 0.0 |]; [| -156.0; 59.0; -42.0; 6.0; 19.0; -20.0; -10.0; -12.0; 0.0 |]; [| 64.0; -152.0; 62.0; -8.0; 32.0; -41.0; 19.0; -11.0; 0.0 |]; [| 124.0; 621.0; -145.0; 208.0; 54.0; -57.0; 30.0; 15.0; 0.0 |]; [| -23437.0; -2634.0; 6601.0; 6259.0; -1507.0; -1821.0; 2620.0; -2115.0;-1489.0 |]; [| 62911.0;-119919.0; 79336.0; 17814.0;-24241.0; 12068.0; 8306.0; -4893.0; 8902.0 |]; [| 389061.0;-262125.0;-44088.0; 8387.0;-22976.0; -2093.0; -615.0; -9720.0; 6633.0 |]; [| -412235.0;-157046.0;-31430.0; 37817.0; -9740.0; -13.0; -7449.0; 9644.0; 0.0 |] |] and sa = [| [| -29.0; -1.0; 9.0; 6.0; -6.0; 5.0; 4.0; 0.0; 0.0 |]; [| -48.0; -125.0; -26.0; -37.0; 18.0; -13.0; -20.0; -2.0; 0.0 |]; [| -150.0; -46.0; 68.0; 54.0; 14.0; 24.0; -28.0; 22.0; 0.0 |]; [| -621.0; 532.0; -694.0; -20.0; 192.0; -94.0; 71.0; -73.0; 0.0 |]; [| -14614.0;-19828.0; -5869.0; 1881.0; -4372.0; -2255.0; 782.0; 930.0; 913.0 |]; [| 139737.0; 0.0; 24667.0; 51123.0; -5102.0; 7429.0; -4095.0; -1976.0;-9566.0 |]; [| -138081.0; 0.0; 37205.0;-49039.0;-41901.0;-33872.0;-27037.0;-12474.0;18797.0 |]; [| 0.0; 28492.0;133236.0; 69654.0; 52322.0;-49577.0;-26430.0; -3593.0; 0.0 |] |] (* tables giving the trigonometric terms to be added to the mean elements of the mean longitudes . *) and kq = [| [| 3086.0; 15746.0; 69613.0; 59899.0; 75645.0; 88306.0; 12661.0; 2658.0; 0.0; 0.0 |]; [| 21863.0; 32794.0; 10931.0; 73.0; 4387.0; 26934.0; 1473.0; 2157.0; 0.0; 0.0 |]; [| 10.0; 16002.0; 21863.0; 10931.0; 1473.0; 32004.0; 4387.0; 73.0; 0.0; 0.0 |]; [| 10.0; 6345.0; 7818.0; 1107.0; 15636.0; 7077.0; 8184.0; 532.0; 10.0; 0.0 |]; [| 19.0; 1760.0; 1454.0; 287.0; 1167.0; 880.0; 574.0; 2640.0; 19.0;1454.0 |]; [| 19.0; 574.0; 287.0; 306.0; 1760.0; 12.0; 31.0; 38.0; 19.0; 574.0 |]; [| 4.0; 204.0; 177.0; 8.0; 31.0; 200.0; 1265.0; 102.0; 4.0; 204.0 |]; [| 4.0; 102.0; 106.0; 8.0; 98.0; 1367.0; 487.0; 204.0; 4.0; 102.0 |] |] and cl = [| [| 21.0; -95.0; -157.0; 41.0; -5.0; 42.0; 23.0; 30.0; 0.0; 0.0 |]; [| -160.0; -313.0; -235.0; 60.0; -74.0; -76.0; -27.0; 34.0; 0.0; 0.0 |]; [| -325.0; -322.0; -79.0; 232.0; -52.0; 97.0; 55.0; -41.0; 0.0; 0.0 |]; [| 2268.0; -979.0; 802.0; 602.0; -668.0; -33.0; 345.0; 201.0; -55.0; 0.0 |]; [| 7610.0; -4997.0;-7689.0;-5841.0;-2617.0; 1115.0; -748.0; -607.0; 6074.0; 354.0 |]; [| -18549.0; 30125.0;20012.0; -730.0; 824.0; 23.0; 1289.0; -352.0;-14767.0;-2062.0 |]; [| -135245.0;-14594.0; 4197.0;-4030.0;-5630.0;-2898.0; 2540.0; -306.0; 2939.0; 1986.0 |]; [| 89948.0; 2103.0; 8963.0; 2695.0; 3682.0; 1648.0; 866.0; -154.0; -1963.0; -283.0 |] |] and sl = [| [| -342.0; 136.0; -23.0; 62.0; 66.0; -52.0; -33.0; 17.0; 0.0; 0.0 |]; [| 524.0; -149.0; -35.0; 117.0; 151.0; 122.0; -71.0; -62.0; 0.0; 0.0 |]; [| -105.0; -137.0; 258.0; 35.0; -116.0; -88.0; -112.0; -80.0; 0.0; 0.0 |]; [| 854.0; -205.0; -936.0; -240.0; 140.0; -341.0; -97.0; -232.0; 536.0; 0.0 |]; [| -56980.0; 8016.0; 1012.0; 1448.0;-3024.0;-3710.0; 318.0; 503.0; 3767.0; 577.0 |]; [| 138606.0;-13478.0;-4964.0; 1441.0;-1319.0;-1482.0; 427.0; 1236.0; -9167.0;-1918.0 |]; [| 71234.0;-41116.0; 5334.0;-4935.0;-1848.0; 66.0; 434.0;-1748.0; 3780.0; -701.0 |]; [| -47645.0; 11647.0; 2166.0; 3194.0; 679.0; 0.0; -244.0; -419.0; -2531.0; 48.0 |] |] (* Normalize angle into the range -pi <= A < +pi. *) let anpm a = let w = mod_float a twopi in if abs_float w >= pic then begin if a < 0.0 then w +. twopi else w -. twopi end else w (* The reference frame is equatorial and is with respect to the * mean equator and equinox of epoch j2000. *) let planetpv epoch np pv = time : julian millennia since j2000 . let t = ((epoch.(0) -. j2000) +. epoch.(1)) /. jmillenia in (* compute the mean elements. *) let da = ref (a.(np).(0) +. (a.(np).(1) +. a.(np).(2) *. t ) *. t) and dl = ref ((3600.0 *. dlm.(np).(0) +. (dlm.(np).(1) +. dlm.(np).(2) *. t ) *. t) *. a2r) and de = e.(np).(0) +. (e.(np).(1) +. e.(np).(2) *. t ) *. t and dp = anpm ((3600.0 *. pi.(np).(0) +. (pi.(np).(1) +. pi.(np).(2) *. t ) *. t ) *. a2r ) and di = (3600.0 *. dinc.(np).(0) +. (dinc.(np).(1) +. dinc.(np).(2) *. t ) *. t ) *. a2r and doh = anpm ((3600.0 *. omega.(np).(0) +. (omega.(np).(1) +. omega.(np).(2) *. t ) *. t ) *. a2r ) (* apply the trigonometric terms. *) and dmu = 0.35953620 *. t in (* loop invariant *) let kp = kp.(np) and kq = kq.(np) and ca = ca.(np) and sa = sa.(np) and cl = cl.(np) and sl = sl.(np) in for k = 0 to 7 do let arga = kp.(k) *. dmu and argl = kq.(k) *. dmu in da := !da +. (ca.(k) *. cos arga +. sa.(k) *. sin arga) *. 0.0000001; dl := !dl +. (cl.(k) *. cos argl +. sl.(k) *. sin argl) *. 0.0000001 done; begin let arga = kp.(8) *. dmu in da := !da +. t *. (ca.(8) *. cos arga +. sa.(8) *. sin arga ) *. 0.0000001; for k = 8 to 9 do let argl = kq.(k) *. dmu in dl := !dl +. t *. ( cl.(k) *. cos argl +. sl.(k) *. sin argl ) *. 0.0000001 done; end; dl := mod_float !dl twopi; iterative solution of kepler 's equation to get eccentric anomaly . let am = !dl -. dp in let ae = ref (am +. de *. sin am) and k = ref 0 in let dae = ref ((am -. !ae +. de *. sin !ae) /. (1.0 -. de *. cos !ae)) in ae := !ae +. !dae; incr k; while !k < 10 || abs_float !dae >= 1e-12 do dae := (am -. !ae +. de *. sin !ae) /. (1.0 -. de *. cos !ae); ae := !ae +. !dae; incr k done; (* true anomaly. *) let ae2 = !ae /. 2.0 in let at = 2.0 *. atan2 (sqrt ((1.0 +. de) /. (1.0 -. de)) *. sin ae2) (cos ae2) (* distance (au) and speed (radians per day). *) and r = !da *. (1.0 -. de *. cos !ae) and v = gaussk *. sqrt ((1.0 +. 1.0 /. amas.(np) ) /. (!da *. !da *. !da)) and si2 = sin (di /. 2.0) in let xq = si2 *. cos doh and xp = si2 *. sin doh and tl = at +. dp in let xsw = sin tl and xcw = cos tl in let xm2 = 2.0 *. (xp *. xcw -. xq *. xsw ) and xf = !da /. sqrt (1.0 -. de *. de) and ci2 = cos (di /. 2.0) in let xms = (de *. sin dp +. xsw) *. xf and xmc = (de *. cos dp +. xcw) *. xf and xpxq2 = 2.0 *. xp *. xq in position ( , y , z in au ) . let x = r *. (xcw -. xm2 *. xp) and y = r *. (xsw +. xm2 *. xq) and z = r *. (-.xm2 *. ci2) in (* rotate to equatorial. *) pv.(0).(0) <- x; pv.(0).(1) <- y *. coseps -. z *. sineps; pv.(0).(2) <- y *. sineps +. z *. coseps; velocity ( j2000 ecliptic xdot , ydot , in au / d ) . let x = v *. ((-1.0 +. 2.0 *. xp *. xp) *. xms +. xpxq2 *. xmc) and y = v *. (( 1.0 -. 2.0 *. xq *. xq ) *. xmc -. xpxq2 *. xms) and z = v *. (2.0 *. ci2 *. (xp *. xms +. xq *. xmc)) in (* rotate to equatorial *) pv.(1).(0) <- x; pv.(1).(1) <- y *. coseps -. z *. sineps; pv.(1).(2) <- y *. sineps +. z *. coseps (* Computes RA, Declination, and distance from a state vector returned by * planetpv. *) let radecdist state rdd = (* Distance *) rdd.(2) <- sqrt (state.(0).(0) *. state.(0).(0) +. state.(0).(1) *. state.(0).(1) +. state.(0).(2) *. state.(0).(2)); (* RA *) rdd.(0) <- atan2 state.(0).(1) state.(0).(0) *. r2h; if rdd.(0) < 0.0 then rdd.(0) <- rdd.(0) +. 24.0; (* Declination *) rdd.(1) <- asin (state.(0).(2) /. rdd.(2)) *. r2d Entry point . Calculate RA and Dec for noon on every day in 1900 - 2100 let run i = let jd = [| 0.0; 0.0 |] and pv = [| [| 0.0; 0.0; 0.0 |]; [| 0.0; 0.0; 0.0 |] |] and position = [| 0.0; 0.0; 0.0 |] in Array.init i (fun i -> jd.(0) <- j2000 +. (float (i + 1)); jd.(1) <- 0.0; Array.init 8 (fun p -> planetpv jd p pv; radecdist pv position; ( position.(0), position.(1) ))) let result_1 = [|17.00, -26.06; 12.34, 1.29; 6.83, 22.95; 0.04, -1.26; 2.30, 12.54; 2.93, 14.35; 21.27, -16.57; 20.41, -19.04|] open Micro_bench_types exception Err of (int * float * float) let check_1 _ result = let result = result.(0) in try Array.iteri (fun i (a,b) -> let a', b' = result_1.(i) in if not (abs_float (a' -. a) <= 0.01 && abs_float (b' -. b) <= 0.01) then raise (Err (i, a, b))) result; Ok with Err (i, a, b) -> let (a', b') = result_1.(i) in let s = string_of_int i ^ ": result " ^ string_of_float a ^ " " ^ string_of_float b ^ " expected " ^ string_of_float a' ^ " " ^ string_of_float b' in Error s let functions = [ "bench", Int (run, (fun i -> i), check_1, [ Range (20, 100), Short ]) ] let () = add functions
null
https://raw.githubusercontent.com/OCamlPro/operf-micro/d5d2bf2068204b889321b0c5a7bc0d079c0fca80/share/operf-micro/benchmarks/almabench/almabench.ml
ocaml
number of days to include in test tables for trigonometric terms to be added to the mean elements of the semi-major axes. tables giving the trigonometric terms to be added to the mean elements of the mean longitudes . Normalize angle into the range -pi <= A < +pi. The reference frame is equatorial and is with respect to the * mean equator and equinox of epoch j2000. compute the mean elements. apply the trigonometric terms. loop invariant true anomaly. distance (au) and speed (radians per day). rotate to equatorial. rotate to equatorial Computes RA, Declination, and distance from a state vector returned by * planetpv. Distance RA Declination
* ALMABENCH 1.0.1 * OCaml version * * A number - crunching benchmark designed for cross - language and vendor * comparisons . * * Written by , from versions for * C++ and java . * * No rights reserved . This is public domain software , for use by anyone . * * This program calculates the daily ephemeris ( at noon ) for the years * 2000 - 2099 using an algorithm developed by , , J. * , and of the Bureau des * Longitudes , Paris , France ) , as detailed in Astronomy & Astrophysics * 282 , 663 ( 1994 ) * * Note that the code herein is design for the purpose of testing * computational performance ; error handling and other such " niceties " * is virtually non - existent . * * Actual ( and oft - updated ) benchmark results can be found at : * * * Please do not use this information or algorithm in any way that might * upset the balance of the universe or otherwise cause planets to impact * upon one another . * ALMABENCH 1.0.1 * OCaml version * * A number-crunching benchmark designed for cross-language and vendor * comparisons. * * Written by Shawn Wagner, from Scott Robert Ladd's versions for * C++ and java. * * No rights reserved. This is public domain software, for use by anyone. * * This program calculates the daily ephemeris (at noon) for the years * 2000-2099 using an algorithm developed by J.L. Simon, P. Bretagnon, J. * Chapront, M. Chapront-Touze, G. Francou and J. Laskar of the Bureau des * Longitudes, Paris, France), as detailed in Astronomy & Astrophysics * 282, 663 (1994) * * Note that the code herein is design for the purpose of testing * computational performance; error handling and other such "niceties" * is virtually non-existent. * * Actual (and oft-updated) benchmark results can be found at: * * * Please do not use this information or algorithm in any way that might * upset the balance of the universe or otherwise cause planets to impact * upon one another. *) let pic = 3.14159265358979323846 and j2000 = 2451545.0 and jcentury = 36525.0 and jmillenia = 365250.0 let twopi = 2.0 *. pic and a2r = pic /. 648000.0 and r2h = 12.0 /. pic and r2d = 180.0 /. pic and gaussk = 0.01720209895 let test_loops = 5 ( \ * was : 20 * \ ) and = 36525 sin and cos of j2000 mean obliquity ( iau 1976 ) and sineps = 0.3977771559319137 and coseps = 0.9174820620691818 and amas = [| 6023600.0; 408523.5; 328900.5; 3098710.0; 1047.355; 3498.5; 22869.0; 19314.0 |] * tables giving the mean keplerian elements , limited to t**2 terms : * a semi - major axis ( au ) * dlm mean longitude ( degree and arcsecond ) * e eccentricity * pi longitude of the perihelion ( degree and arcsecond ) * dinc inclination ( degree and arcsecond ) * omega longitude of the ascending node ( degree and arcsecond ) * tables giving the mean keplerian elements, limited to t**2 terms: * a semi-major axis (au) * dlm mean longitude (degree and arcsecond) * e eccentricity * pi longitude of the perihelion (degree and arcsecond) * dinc inclination (degree and arcsecond) * omega longitude of the ascending node (degree and arcsecond) *) and a = [| [| 0.3870983098; 0.0; 0.0 |]; [| 0.7233298200; 0.0; 0.0 |]; [| 1.0000010178; 0.0; 0.0 |]; [| 1.5236793419; 3e-10; 0.0 |]; [| 5.2026032092; 19132e-10; -39e-10 |]; [| 9.5549091915; -0.0000213896; 444e-10 |]; [| 19.2184460618; -3716e-10; 979e-10 |]; [| 30.1103868694; -16635e-10; 686e-10 |] |] and dlm = [| [| 252.25090552; 5381016286.88982; -1.92789 |]; [| 181.97980085; 2106641364.33548; 0.59381 |]; [| 100.46645683; 1295977422.83429; -2.04411 |]; [| 355.43299958; 689050774.93988; 0.94264 |]; [| 34.35151874; 109256603.77991; -30.60378 |]; [| 50.07744430; 43996098.55732; 75.61614 |]; [| 314.05500511; 15424811.93933; -1.75083 |]; [| 304.34866548; 7865503.20744; 0.21103 |] |] and e = [| [| 0.2056317526; 0.0002040653; -28349e-10 |]; [| 0.0067719164; -0.0004776521; 98127e-10 |]; [| 0.0167086342; -0.0004203654; -0.0000126734 |]; [| 0.0934006477; 0.0009048438; -80641e-10 |]; [| 0.0484979255; 0.0016322542; -0.0000471366 |]; [| 0.0555481426; -0.0034664062; -0.0000643639 |]; [| 0.0463812221; -0.0002729293; 0.0000078913 |]; [| 0.0094557470; 0.0000603263; 0.0 |] |] and pi = [| [| 77.45611904; 5719.11590; -4.83016 |]; [| 131.56370300; 175.48640; -498.48184 |]; [| 102.93734808; 11612.35290; 53.27577 |]; [| 336.06023395; 15980.45908; -62.32800 |]; [| 14.33120687; 7758.75163; 259.95938 |]; [| 93.05723748; 20395.49439; 190.25952 |]; [| 173.00529106; 3215.56238; -34.09288 |]; [| 48.12027554; 1050.71912; 27.39717 |] |] and dinc = [| [| 7.00498625; -214.25629; 0.28977 |]; [| 3.39466189; -30.84437; -11.67836 |]; [| 0.0; 469.97289; -3.35053 |]; [| 1.84972648; -293.31722; -8.11830 |]; [| 1.30326698; -71.55890; 11.95297 |]; [| 2.48887878; 91.85195; -17.66225 |]; [| 0.77319689; -60.72723; 1.25759 |]; [| 1.76995259; 8.12333; 0.08135 |] |] and omega = [| [| 48.33089304; -4515.21727; -31.79892 |]; [| 76.67992019; -10008.48154; -51.32614 |]; [| 174.87317577; -8679.27034; 15.34191 |]; [| 49.55809321; -10620.90088; -230.57416 |]; [| 100.46440702; 6362.03561; 326.52178 |]; [| 113.66550252; -9240.19942; -66.23743 |]; [| 74.00595701; 2669.15033; 145.93964 |]; [| 131.78405702; -221.94322; -0.78728 |] |] and kp = [| [| 69613.0; 75645.0; 88306.0; 59899.0; 15746.0; 71087.0; 142173.0; 3086.0; 0.0 |]; [| 21863.0; 32794.0; 26934.0; 10931.0; 26250.0; 43725.0; 53867.0; 28939.0; 0.0 |]; [| 16002.0; 21863.0; 32004.0; 10931.0; 14529.0; 16368.0; 15318.0; 32794.0; 0.0 |]; [| 6345.0; 7818.0; 15636.0; 7077.0; 8184.0; 14163.0; 1107.0; 4872.0; 0.0 |]; [| 1760.0; 1454.0; 1167.0; 880.0; 287.0; 2640.0; 19.0; 2047.0; 1454.0 |]; [| 574.0; 0.0; 880.0; 287.0; 19.0; 1760.0; 1167.0; 306.0; 574.0 |]; [| 204.0; 0.0; 177.0; 1265.0; 4.0; 385.0; 200.0; 208.0; 204.0 |]; [| 0.0; 102.0; 106.0; 4.0; 98.0; 1367.0; 487.0; 204.0; 0.0 |] |] and ca = [| [| 4.0; -13.0; 11.0; -9.0; -9.0; -3.0; -1.0; 4.0; 0.0 |]; [| -156.0; 59.0; -42.0; 6.0; 19.0; -20.0; -10.0; -12.0; 0.0 |]; [| 64.0; -152.0; 62.0; -8.0; 32.0; -41.0; 19.0; -11.0; 0.0 |]; [| 124.0; 621.0; -145.0; 208.0; 54.0; -57.0; 30.0; 15.0; 0.0 |]; [| -23437.0; -2634.0; 6601.0; 6259.0; -1507.0; -1821.0; 2620.0; -2115.0;-1489.0 |]; [| 62911.0;-119919.0; 79336.0; 17814.0;-24241.0; 12068.0; 8306.0; -4893.0; 8902.0 |]; [| 389061.0;-262125.0;-44088.0; 8387.0;-22976.0; -2093.0; -615.0; -9720.0; 6633.0 |]; [| -412235.0;-157046.0;-31430.0; 37817.0; -9740.0; -13.0; -7449.0; 9644.0; 0.0 |] |] and sa = [| [| -29.0; -1.0; 9.0; 6.0; -6.0; 5.0; 4.0; 0.0; 0.0 |]; [| -48.0; -125.0; -26.0; -37.0; 18.0; -13.0; -20.0; -2.0; 0.0 |]; [| -150.0; -46.0; 68.0; 54.0; 14.0; 24.0; -28.0; 22.0; 0.0 |]; [| -621.0; 532.0; -694.0; -20.0; 192.0; -94.0; 71.0; -73.0; 0.0 |]; [| -14614.0;-19828.0; -5869.0; 1881.0; -4372.0; -2255.0; 782.0; 930.0; 913.0 |]; [| 139737.0; 0.0; 24667.0; 51123.0; -5102.0; 7429.0; -4095.0; -1976.0;-9566.0 |]; [| -138081.0; 0.0; 37205.0;-49039.0;-41901.0;-33872.0;-27037.0;-12474.0;18797.0 |]; [| 0.0; 28492.0;133236.0; 69654.0; 52322.0;-49577.0;-26430.0; -3593.0; 0.0 |] |] and kq = [| [| 3086.0; 15746.0; 69613.0; 59899.0; 75645.0; 88306.0; 12661.0; 2658.0; 0.0; 0.0 |]; [| 21863.0; 32794.0; 10931.0; 73.0; 4387.0; 26934.0; 1473.0; 2157.0; 0.0; 0.0 |]; [| 10.0; 16002.0; 21863.0; 10931.0; 1473.0; 32004.0; 4387.0; 73.0; 0.0; 0.0 |]; [| 10.0; 6345.0; 7818.0; 1107.0; 15636.0; 7077.0; 8184.0; 532.0; 10.0; 0.0 |]; [| 19.0; 1760.0; 1454.0; 287.0; 1167.0; 880.0; 574.0; 2640.0; 19.0;1454.0 |]; [| 19.0; 574.0; 287.0; 306.0; 1760.0; 12.0; 31.0; 38.0; 19.0; 574.0 |]; [| 4.0; 204.0; 177.0; 8.0; 31.0; 200.0; 1265.0; 102.0; 4.0; 204.0 |]; [| 4.0; 102.0; 106.0; 8.0; 98.0; 1367.0; 487.0; 204.0; 4.0; 102.0 |] |] and cl = [| [| 21.0; -95.0; -157.0; 41.0; -5.0; 42.0; 23.0; 30.0; 0.0; 0.0 |]; [| -160.0; -313.0; -235.0; 60.0; -74.0; -76.0; -27.0; 34.0; 0.0; 0.0 |]; [| -325.0; -322.0; -79.0; 232.0; -52.0; 97.0; 55.0; -41.0; 0.0; 0.0 |]; [| 2268.0; -979.0; 802.0; 602.0; -668.0; -33.0; 345.0; 201.0; -55.0; 0.0 |]; [| 7610.0; -4997.0;-7689.0;-5841.0;-2617.0; 1115.0; -748.0; -607.0; 6074.0; 354.0 |]; [| -18549.0; 30125.0;20012.0; -730.0; 824.0; 23.0; 1289.0; -352.0;-14767.0;-2062.0 |]; [| -135245.0;-14594.0; 4197.0;-4030.0;-5630.0;-2898.0; 2540.0; -306.0; 2939.0; 1986.0 |]; [| 89948.0; 2103.0; 8963.0; 2695.0; 3682.0; 1648.0; 866.0; -154.0; -1963.0; -283.0 |] |] and sl = [| [| -342.0; 136.0; -23.0; 62.0; 66.0; -52.0; -33.0; 17.0; 0.0; 0.0 |]; [| 524.0; -149.0; -35.0; 117.0; 151.0; 122.0; -71.0; -62.0; 0.0; 0.0 |]; [| -105.0; -137.0; 258.0; 35.0; -116.0; -88.0; -112.0; -80.0; 0.0; 0.0 |]; [| 854.0; -205.0; -936.0; -240.0; 140.0; -341.0; -97.0; -232.0; 536.0; 0.0 |]; [| -56980.0; 8016.0; 1012.0; 1448.0;-3024.0;-3710.0; 318.0; 503.0; 3767.0; 577.0 |]; [| 138606.0;-13478.0;-4964.0; 1441.0;-1319.0;-1482.0; 427.0; 1236.0; -9167.0;-1918.0 |]; [| 71234.0;-41116.0; 5334.0;-4935.0;-1848.0; 66.0; 434.0;-1748.0; 3780.0; -701.0 |]; [| -47645.0; 11647.0; 2166.0; 3194.0; 679.0; 0.0; -244.0; -419.0; -2531.0; 48.0 |] |] let anpm a = let w = mod_float a twopi in if abs_float w >= pic then begin if a < 0.0 then w +. twopi else w -. twopi end else w let planetpv epoch np pv = time : julian millennia since j2000 . let t = ((epoch.(0) -. j2000) +. epoch.(1)) /. jmillenia in let da = ref (a.(np).(0) +. (a.(np).(1) +. a.(np).(2) *. t ) *. t) and dl = ref ((3600.0 *. dlm.(np).(0) +. (dlm.(np).(1) +. dlm.(np).(2) *. t ) *. t) *. a2r) and de = e.(np).(0) +. (e.(np).(1) +. e.(np).(2) *. t ) *. t and dp = anpm ((3600.0 *. pi.(np).(0) +. (pi.(np).(1) +. pi.(np).(2) *. t ) *. t ) *. a2r ) and di = (3600.0 *. dinc.(np).(0) +. (dinc.(np).(1) +. dinc.(np).(2) *. t ) *. t ) *. a2r and doh = anpm ((3600.0 *. omega.(np).(0) +. (omega.(np).(1) +. omega.(np).(2) *. t ) *. t ) *. a2r ) and dmu = 0.35953620 *. t in let kp = kp.(np) and kq = kq.(np) and ca = ca.(np) and sa = sa.(np) and cl = cl.(np) and sl = sl.(np) in for k = 0 to 7 do let arga = kp.(k) *. dmu and argl = kq.(k) *. dmu in da := !da +. (ca.(k) *. cos arga +. sa.(k) *. sin arga) *. 0.0000001; dl := !dl +. (cl.(k) *. cos argl +. sl.(k) *. sin argl) *. 0.0000001 done; begin let arga = kp.(8) *. dmu in da := !da +. t *. (ca.(8) *. cos arga +. sa.(8) *. sin arga ) *. 0.0000001; for k = 8 to 9 do let argl = kq.(k) *. dmu in dl := !dl +. t *. ( cl.(k) *. cos argl +. sl.(k) *. sin argl ) *. 0.0000001 done; end; dl := mod_float !dl twopi; iterative solution of kepler 's equation to get eccentric anomaly . let am = !dl -. dp in let ae = ref (am +. de *. sin am) and k = ref 0 in let dae = ref ((am -. !ae +. de *. sin !ae) /. (1.0 -. de *. cos !ae)) in ae := !ae +. !dae; incr k; while !k < 10 || abs_float !dae >= 1e-12 do dae := (am -. !ae +. de *. sin !ae) /. (1.0 -. de *. cos !ae); ae := !ae +. !dae; incr k done; let ae2 = !ae /. 2.0 in let at = 2.0 *. atan2 (sqrt ((1.0 +. de) /. (1.0 -. de)) *. sin ae2) (cos ae2) and r = !da *. (1.0 -. de *. cos !ae) and v = gaussk *. sqrt ((1.0 +. 1.0 /. amas.(np) ) /. (!da *. !da *. !da)) and si2 = sin (di /. 2.0) in let xq = si2 *. cos doh and xp = si2 *. sin doh and tl = at +. dp in let xsw = sin tl and xcw = cos tl in let xm2 = 2.0 *. (xp *. xcw -. xq *. xsw ) and xf = !da /. sqrt (1.0 -. de *. de) and ci2 = cos (di /. 2.0) in let xms = (de *. sin dp +. xsw) *. xf and xmc = (de *. cos dp +. xcw) *. xf and xpxq2 = 2.0 *. xp *. xq in position ( , y , z in au ) . let x = r *. (xcw -. xm2 *. xp) and y = r *. (xsw +. xm2 *. xq) and z = r *. (-.xm2 *. ci2) in pv.(0).(0) <- x; pv.(0).(1) <- y *. coseps -. z *. sineps; pv.(0).(2) <- y *. sineps +. z *. coseps; velocity ( j2000 ecliptic xdot , ydot , in au / d ) . let x = v *. ((-1.0 +. 2.0 *. xp *. xp) *. xms +. xpxq2 *. xmc) and y = v *. (( 1.0 -. 2.0 *. xq *. xq ) *. xmc -. xpxq2 *. xms) and z = v *. (2.0 *. ci2 *. (xp *. xms +. xq *. xmc)) in pv.(1).(0) <- x; pv.(1).(1) <- y *. coseps -. z *. sineps; pv.(1).(2) <- y *. sineps +. z *. coseps let radecdist state rdd = rdd.(2) <- sqrt (state.(0).(0) *. state.(0).(0) +. state.(0).(1) *. state.(0).(1) +. state.(0).(2) *. state.(0).(2)); rdd.(0) <- atan2 state.(0).(1) state.(0).(0) *. r2h; if rdd.(0) < 0.0 then rdd.(0) <- rdd.(0) +. 24.0; rdd.(1) <- asin (state.(0).(2) /. rdd.(2)) *. r2d Entry point . Calculate RA and Dec for noon on every day in 1900 - 2100 let run i = let jd = [| 0.0; 0.0 |] and pv = [| [| 0.0; 0.0; 0.0 |]; [| 0.0; 0.0; 0.0 |] |] and position = [| 0.0; 0.0; 0.0 |] in Array.init i (fun i -> jd.(0) <- j2000 +. (float (i + 1)); jd.(1) <- 0.0; Array.init 8 (fun p -> planetpv jd p pv; radecdist pv position; ( position.(0), position.(1) ))) let result_1 = [|17.00, -26.06; 12.34, 1.29; 6.83, 22.95; 0.04, -1.26; 2.30, 12.54; 2.93, 14.35; 21.27, -16.57; 20.41, -19.04|] open Micro_bench_types exception Err of (int * float * float) let check_1 _ result = let result = result.(0) in try Array.iteri (fun i (a,b) -> let a', b' = result_1.(i) in if not (abs_float (a' -. a) <= 0.01 && abs_float (b' -. b) <= 0.01) then raise (Err (i, a, b))) result; Ok with Err (i, a, b) -> let (a', b') = result_1.(i) in let s = string_of_int i ^ ": result " ^ string_of_float a ^ " " ^ string_of_float b ^ " expected " ^ string_of_float a' ^ " " ^ string_of_float b' in Error s let functions = [ "bench", Int (run, (fun i -> i), check_1, [ Range (20, 100), Short ]) ] let () = add functions
552a4f44d4013f9060d352cb4a153f3ccf97c143894b56c8beec3bf1e2c17567
ghcjs/jsaddle-dom
Node.hs
# LANGUAGE PatternSynonyms # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.Node (getRootNode, getRootNode_, hasChildNodes, hasChildNodes_, normalize, cloneNode, cloneNode_, isEqualNode, isEqualNode_, isSameNode, isSameNode_, compareDocumentPosition, compareDocumentPosition_, contains, contains_, lookupPrefix, lookupPrefix_, lookupPrefixUnsafe, lookupPrefixUnchecked, lookupNamespaceURI, lookupNamespaceURI_, lookupNamespaceURIUnsafe, lookupNamespaceURIUnchecked, isDefaultNamespace, isDefaultNamespace_, insertBefore, insertBefore_, appendChild, appendChild_, replaceChild, replaceChild_, removeChild, removeChild_, pattern ELEMENT_NODE, pattern ATTRIBUTE_NODE, pattern TEXT_NODE, pattern CDATA_SECTION_NODE, pattern ENTITY_REFERENCE_NODE, pattern ENTITY_NODE, pattern PROCESSING_INSTRUCTION_NODE, pattern COMMENT_NODE, pattern DOCUMENT_NODE, pattern DOCUMENT_TYPE_NODE, pattern DOCUMENT_FRAGMENT_NODE, pattern NOTATION_NODE, pattern DOCUMENT_POSITION_DISCONNECTED, pattern DOCUMENT_POSITION_PRECEDING, pattern DOCUMENT_POSITION_FOLLOWING, pattern DOCUMENT_POSITION_CONTAINS, pattern DOCUMENT_POSITION_CONTAINED_BY, pattern DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, getNodeType, getNodeName, getBaseURI, getIsConnected, getOwnerDocument, getOwnerDocumentUnsafe, getOwnerDocumentUnchecked, getParentNode, getParentNodeUnsafe, getParentNodeUnchecked, getParentElement, getParentElementUnsafe, getParentElementUnchecked, getChildNodes, getFirstChild, getFirstChildUnsafe, getFirstChildUnchecked, getLastChild, getLastChildUnsafe, getLastChildUnchecked, getPreviousSibling, getPreviousSiblingUnsafe, getPreviousSiblingUnchecked, getNextSibling, getNextSiblingUnsafe, getNextSiblingUnchecked, setNodeValue, getNodeValue, getNodeValueUnsafe, getNodeValueUnchecked, setTextContent, getTextContent, getTextContentUnsafe, getTextContentUnchecked, Node(..), gTypeNode, IsNode, toNode) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/Node.getRootNode Mozilla Node.getRootNode documentation > getRootNode :: (MonadDOM m, IsNode self) => self -> Maybe GetRootNodeOptions -> m Node getRootNode self options = liftDOM (((toNode self) ^. jsf "getRootNode" [toJSVal options]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.getRootNode Mozilla Node.getRootNode documentation > getRootNode_ :: (MonadDOM m, IsNode self) => self -> Maybe GetRootNodeOptions -> m () getRootNode_ self options = liftDOM (void ((toNode self) ^. jsf "getRootNode" [toJSVal options])) -- | <-US/docs/Web/API/Node.hasChildNodes Mozilla Node.hasChildNodes documentation> hasChildNodes :: (MonadDOM m, IsNode self) => self -> m Bool hasChildNodes self = liftDOM (((toNode self) ^. jsf "hasChildNodes" ()) >>= valToBool) -- | <-US/docs/Web/API/Node.hasChildNodes Mozilla Node.hasChildNodes documentation> hasChildNodes_ :: (MonadDOM m, IsNode self) => self -> m () hasChildNodes_ self = liftDOM (void ((toNode self) ^. jsf "hasChildNodes" ())) -- | <-US/docs/Web/API/Node.normalize Mozilla Node.normalize documentation> normalize :: (MonadDOM m, IsNode self) => self -> m () normalize self = liftDOM (void ((toNode self) ^. jsf "normalize" ())) | < Node.cloneNode documentation > cloneNode :: (MonadDOM m, IsNode self) => self -> Bool -> m Node cloneNode self deep = liftDOM (((toNode self) ^. jsf "cloneNode" [toJSVal deep]) >>= fromJSValUnchecked) | < Node.cloneNode documentation > cloneNode_ :: (MonadDOM m, IsNode self) => self -> Bool -> m () cloneNode_ self deep = liftDOM (void ((toNode self) ^. jsf "cloneNode" [toJSVal deep])) | < -US/docs/Web/API/Node.isEqualNode Mozilla documentation > isEqualNode :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m Bool isEqualNode self other = liftDOM (((toNode self) ^. jsf "isEqualNode" [toJSVal other]) >>= valToBool) | < -US/docs/Web/API/Node.isEqualNode Mozilla documentation > isEqualNode_ :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m () isEqualNode_ self other = liftDOM (void ((toNode self) ^. jsf "isEqualNode" [toJSVal other])) | < -US/docs/Web/API/Node.isSameNode Mozilla Node.isSameNode documentation > isSameNode :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m Bool isSameNode self other = liftDOM (((toNode self) ^. jsf "isSameNode" [toJSVal other]) >>= valToBool) | < -US/docs/Web/API/Node.isSameNode Mozilla Node.isSameNode documentation > isSameNode_ :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m () isSameNode_ self other = liftDOM (void ((toNode self) ^. jsf "isSameNode" [toJSVal other])) -- | <-US/docs/Web/API/Node.compareDocumentPosition Mozilla Node.compareDocumentPosition documentation> compareDocumentPosition :: (MonadDOM m, IsNode self, IsNode other) => self -> other -> m Word compareDocumentPosition self other = liftDOM (round <$> (((toNode self) ^. jsf "compareDocumentPosition" [toJSVal other]) >>= valToNumber)) -- | <-US/docs/Web/API/Node.compareDocumentPosition Mozilla Node.compareDocumentPosition documentation> compareDocumentPosition_ :: (MonadDOM m, IsNode self, IsNode other) => self -> other -> m () compareDocumentPosition_ self other = liftDOM (void ((toNode self) ^. jsf "compareDocumentPosition" [toJSVal other])) | < -US/docs/Web/API/Node.contains Mozilla Node.contains documentation > contains :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m Bool contains self other = liftDOM (((toNode self) ^. jsf "contains" [toJSVal other]) >>= valToBool) | < -US/docs/Web/API/Node.contains Mozilla Node.contains documentation > contains_ :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m () contains_ self other = liftDOM (void ((toNode self) ^. jsf "contains" [toJSVal other])) | < -US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation > lookupPrefix :: (MonadDOM m, IsNode self, ToJSString namespaceURI, FromJSString result) => self -> Maybe namespaceURI -> m (Maybe result) lookupPrefix self namespaceURI = liftDOM (((toNode self) ^. jsf "lookupPrefix" [toJSVal namespaceURI]) >>= fromMaybeJSString) | < -US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation > lookupPrefix_ :: (MonadDOM m, IsNode self, ToJSString namespaceURI) => self -> Maybe namespaceURI -> m () lookupPrefix_ self namespaceURI = liftDOM (void ((toNode self) ^. jsf "lookupPrefix" [toJSVal namespaceURI])) | < -US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation > lookupPrefixUnsafe :: (MonadDOM m, IsNode self, ToJSString namespaceURI, HasCallStack, FromJSString result) => self -> Maybe namespaceURI -> m result lookupPrefixUnsafe self namespaceURI = liftDOM ((((toNode self) ^. jsf "lookupPrefix" [toJSVal namespaceURI]) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation > lookupPrefixUnchecked :: (MonadDOM m, IsNode self, ToJSString namespaceURI, FromJSString result) => self -> Maybe namespaceURI -> m result lookupPrefixUnchecked self namespaceURI = liftDOM (((toNode self) ^. jsf "lookupPrefix" [toJSVal namespaceURI]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation > lookupNamespaceURI :: (MonadDOM m, IsNode self, ToJSString prefix, FromJSString result) => self -> Maybe prefix -> m (Maybe result) lookupNamespaceURI self prefix = liftDOM (((toNode self) ^. jsf "lookupNamespaceURI" [toJSVal prefix]) >>= fromMaybeJSString) | < -US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation > lookupNamespaceURI_ :: (MonadDOM m, IsNode self, ToJSString prefix) => self -> Maybe prefix -> m () lookupNamespaceURI_ self prefix = liftDOM (void ((toNode self) ^. jsf "lookupNamespaceURI" [toJSVal prefix])) | < -US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation > lookupNamespaceURIUnsafe :: (MonadDOM m, IsNode self, ToJSString prefix, HasCallStack, FromJSString result) => self -> Maybe prefix -> m result lookupNamespaceURIUnsafe self prefix = liftDOM ((((toNode self) ^. jsf "lookupNamespaceURI" [toJSVal prefix]) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation > lookupNamespaceURIUnchecked :: (MonadDOM m, IsNode self, ToJSString prefix, FromJSString result) => self -> Maybe prefix -> m result lookupNamespaceURIUnchecked self prefix = liftDOM (((toNode self) ^. jsf "lookupNamespaceURI" [toJSVal prefix]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.isDefaultNamespace Mozilla Node.isDefaultNamespace documentation > isDefaultNamespace :: (MonadDOM m, IsNode self, ToJSString namespaceURI) => self -> Maybe namespaceURI -> m Bool isDefaultNamespace self namespaceURI = liftDOM (((toNode self) ^. jsf "isDefaultNamespace" [toJSVal namespaceURI]) >>= valToBool) | < -US/docs/Web/API/Node.isDefaultNamespace Mozilla Node.isDefaultNamespace documentation > isDefaultNamespace_ :: (MonadDOM m, IsNode self, ToJSString namespaceURI) => self -> Maybe namespaceURI -> m () isDefaultNamespace_ self namespaceURI = liftDOM (void ((toNode self) ^. jsf "isDefaultNamespace" [toJSVal namespaceURI])) | < -US/docs/Web/API/Node.insertBefore Mozilla Node.insertBefore documentation > insertBefore :: (MonadDOM m, IsNode self, IsNode node, IsNode child) => self -> node -> Maybe child -> m Node insertBefore self node child = liftDOM (((toNode self) ^. jsf "insertBefore" [toJSVal node, toJSVal child]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.insertBefore Mozilla Node.insertBefore documentation > insertBefore_ :: (MonadDOM m, IsNode self, IsNode node, IsNode child) => self -> node -> Maybe child -> m () insertBefore_ self node child = liftDOM (void ((toNode self) ^. jsf "insertBefore" [toJSVal node, toJSVal child])) | < -US/docs/Web/API/Node.appendChild Mozilla Node.appendChild documentation > appendChild :: (MonadDOM m, IsNode self, IsNode node) => self -> node -> m Node appendChild self node = liftDOM (((toNode self) ^. jsf "appendChild" [toJSVal node]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.appendChild Mozilla Node.appendChild documentation > appendChild_ :: (MonadDOM m, IsNode self, IsNode node) => self -> node -> m () appendChild_ self node = liftDOM (void ((toNode self) ^. jsf "appendChild" [toJSVal node])) | < -US/docs/Web/API/Node.replaceChild Mozilla Node.replaceChild documentation > replaceChild :: (MonadDOM m, IsNode self, IsNode node, IsNode child) => self -> node -> child -> m Node replaceChild self node child = liftDOM (((toNode self) ^. jsf "replaceChild" [toJSVal node, toJSVal child]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.replaceChild Mozilla Node.replaceChild documentation > replaceChild_ :: (MonadDOM m, IsNode self, IsNode node, IsNode child) => self -> node -> child -> m () replaceChild_ self node child = liftDOM (void ((toNode self) ^. jsf "replaceChild" [toJSVal node, toJSVal child])) | < -US/docs/Web/API/Node.removeChild Mozilla Node.removeChild documentation > removeChild :: (MonadDOM m, IsNode self, IsNode child) => self -> child -> m Node removeChild self child = liftDOM (((toNode self) ^. jsf "removeChild" [toJSVal child]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.removeChild Mozilla Node.removeChild documentation > removeChild_ :: (MonadDOM m, IsNode self, IsNode child) => self -> child -> m () removeChild_ self child = liftDOM (void ((toNode self) ^. jsf "removeChild" [toJSVal child])) pattern ELEMENT_NODE = 1 pattern ATTRIBUTE_NODE = 2 pattern TEXT_NODE = 3 pattern CDATA_SECTION_NODE = 4 pattern ENTITY_REFERENCE_NODE = 5 pattern ENTITY_NODE = 6 pattern PROCESSING_INSTRUCTION_NODE = 7 pattern COMMENT_NODE = 8 pattern DOCUMENT_NODE = 9 pattern DOCUMENT_TYPE_NODE = 10 pattern DOCUMENT_FRAGMENT_NODE = 11 pattern NOTATION_NODE = 12 pattern DOCUMENT_POSITION_DISCONNECTED = 1 pattern DOCUMENT_POSITION_PRECEDING = 2 pattern DOCUMENT_POSITION_FOLLOWING = 4 pattern DOCUMENT_POSITION_CONTAINS = 8 pattern DOCUMENT_POSITION_CONTAINED_BY = 16 pattern DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32 | < -US/docs/Web/API/Node.nodeType Mozilla Node.nodeType documentation > getNodeType :: (MonadDOM m, IsNode self) => self -> m Word getNodeType self = liftDOM (round <$> (((toNode self) ^. js "nodeType") >>= valToNumber)) -- | <-US/docs/Web/API/Node.nodeName Mozilla Node.nodeName documentation> getNodeName :: (MonadDOM m, IsNode self, FromJSString result) => self -> m result getNodeName self = liftDOM (((toNode self) ^. js "nodeName") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Node.baseURI Mozilla Node.baseURI documentation> getBaseURI :: (MonadDOM m, IsNode self, FromJSString result) => self -> m result getBaseURI self = liftDOM (((toNode self) ^. js "baseURI") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Node.isConnected Mozilla Node.isConnected documentation> getIsConnected :: (MonadDOM m, IsNode self) => self -> m Bool getIsConnected self = liftDOM (((toNode self) ^. js "isConnected") >>= valToBool) -- | <-US/docs/Web/API/Node.ownerDocument Mozilla Node.ownerDocument documentation> getOwnerDocument :: (MonadDOM m, IsNode self) => self -> m (Maybe Document) getOwnerDocument self = liftDOM (((toNode self) ^. js "ownerDocument") >>= fromJSVal) -- | <-US/docs/Web/API/Node.ownerDocument Mozilla Node.ownerDocument documentation> getOwnerDocumentUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Document getOwnerDocumentUnsafe self = liftDOM ((((toNode self) ^. js "ownerDocument") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <-US/docs/Web/API/Node.ownerDocument Mozilla Node.ownerDocument documentation> getOwnerDocumentUnchecked :: (MonadDOM m, IsNode self) => self -> m Document getOwnerDocumentUnchecked self = liftDOM (((toNode self) ^. js "ownerDocument") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.parentNode Mozilla Node.parentNode documentation > getParentNode :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getParentNode self = liftDOM (((toNode self) ^. js "parentNode") >>= fromJSVal) | < -US/docs/Web/API/Node.parentNode Mozilla Node.parentNode documentation > getParentNodeUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getParentNodeUnsafe self = liftDOM ((((toNode self) ^. js "parentNode") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.parentNode Mozilla Node.parentNode documentation > getParentNodeUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getParentNodeUnchecked self = liftDOM (((toNode self) ^. js "parentNode") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.parentElement Mozilla Node.parentElement documentation > getParentElement :: (MonadDOM m, IsNode self) => self -> m (Maybe Element) getParentElement self = liftDOM (((toNode self) ^. js "parentElement") >>= fromJSVal) | < -US/docs/Web/API/Node.parentElement Mozilla Node.parentElement documentation > getParentElementUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Element getParentElementUnsafe self = liftDOM ((((toNode self) ^. js "parentElement") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.parentElement Mozilla Node.parentElement documentation > getParentElementUnchecked :: (MonadDOM m, IsNode self) => self -> m Element getParentElementUnchecked self = liftDOM (((toNode self) ^. js "parentElement") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.childNodes Mozilla Node.childNodes documentation > getChildNodes :: (MonadDOM m, IsNode self) => self -> m NodeList getChildNodes self = liftDOM (((toNode self) ^. js "childNodes") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.firstChild Mozilla Node.firstChild documentation > getFirstChild :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getFirstChild self = liftDOM (((toNode self) ^. js "firstChild") >>= fromJSVal) | < -US/docs/Web/API/Node.firstChild Mozilla Node.firstChild documentation > getFirstChildUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getFirstChildUnsafe self = liftDOM ((((toNode self) ^. js "firstChild") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.firstChild Mozilla Node.firstChild documentation > getFirstChildUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getFirstChildUnchecked self = liftDOM (((toNode self) ^. js "firstChild") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.lastChild Mozilla Node.lastChild documentation > getLastChild :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getLastChild self = liftDOM (((toNode self) ^. js "lastChild") >>= fromJSVal) | < -US/docs/Web/API/Node.lastChild Mozilla Node.lastChild documentation > getLastChildUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getLastChildUnsafe self = liftDOM ((((toNode self) ^. js "lastChild") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.lastChild Mozilla Node.lastChild documentation > getLastChildUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getLastChildUnchecked self = liftDOM (((toNode self) ^. js "lastChild") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.previousSibling Mozilla Node.previousSibling documentation > getPreviousSibling :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getPreviousSibling self = liftDOM (((toNode self) ^. js "previousSibling") >>= fromJSVal) | < -US/docs/Web/API/Node.previousSibling Mozilla Node.previousSibling documentation > getPreviousSiblingUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getPreviousSiblingUnsafe self = liftDOM ((((toNode self) ^. js "previousSibling") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.previousSibling Mozilla Node.previousSibling documentation > getPreviousSiblingUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getPreviousSiblingUnchecked self = liftDOM (((toNode self) ^. js "previousSibling") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Node.nextSibling Mozilla Node.nextSibling documentation> getNextSibling :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getNextSibling self = liftDOM (((toNode self) ^. js "nextSibling") >>= fromJSVal) -- | <-US/docs/Web/API/Node.nextSibling Mozilla Node.nextSibling documentation> getNextSiblingUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getNextSiblingUnsafe self = liftDOM ((((toNode self) ^. js "nextSibling") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <-US/docs/Web/API/Node.nextSibling Mozilla Node.nextSibling documentation> getNextSiblingUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getNextSiblingUnchecked self = liftDOM (((toNode self) ^. js "nextSibling") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation > setNodeValue :: (MonadDOM m, IsNode self, ToJSString val) => self -> Maybe val -> m () setNodeValue self val = liftDOM ((toNode self) ^. jss "nodeValue" (toJSVal val)) | < -US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation > getNodeValue :: (MonadDOM m, IsNode self, FromJSString result) => self -> m (Maybe result) getNodeValue self = liftDOM (((toNode self) ^. js "nodeValue") >>= fromMaybeJSString) | < -US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation > getNodeValueUnsafe :: (MonadDOM m, IsNode self, HasCallStack, FromJSString result) => self -> m result getNodeValueUnsafe self = liftDOM ((((toNode self) ^. js "nodeValue") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation > getNodeValueUnchecked :: (MonadDOM m, IsNode self, FromJSString result) => self -> m result getNodeValueUnchecked self = liftDOM (((toNode self) ^. js "nodeValue") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation > setTextContent :: (MonadDOM m, IsNode self, ToJSString val) => self -> Maybe val -> m () setTextContent self val = liftDOM ((toNode self) ^. jss "textContent" (toJSVal val)) | < -US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation > getTextContent :: (MonadDOM m, IsNode self, FromJSString result) => self -> m (Maybe result) getTextContent self = liftDOM (((toNode self) ^. js "textContent") >>= fromMaybeJSString) | < -US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation > getTextContentUnsafe :: (MonadDOM m, IsNode self, HasCallStack, FromJSString result) => self -> m result getTextContentUnsafe self = liftDOM ((((toNode self) ^. js "textContent") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation > getTextContentUnchecked :: (MonadDOM m, IsNode self, FromJSString result) => self -> m result getTextContentUnchecked self = liftDOM (((toNode self) ^. js "textContent") >>= fromJSValUnchecked)
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/Node.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | <-US/docs/Web/API/Node.hasChildNodes Mozilla Node.hasChildNodes documentation> | <-US/docs/Web/API/Node.hasChildNodes Mozilla Node.hasChildNodes documentation> | <-US/docs/Web/API/Node.normalize Mozilla Node.normalize documentation> | <-US/docs/Web/API/Node.compareDocumentPosition Mozilla Node.compareDocumentPosition documentation> | <-US/docs/Web/API/Node.compareDocumentPosition Mozilla Node.compareDocumentPosition documentation> | <-US/docs/Web/API/Node.nodeName Mozilla Node.nodeName documentation> | <-US/docs/Web/API/Node.baseURI Mozilla Node.baseURI documentation> | <-US/docs/Web/API/Node.isConnected Mozilla Node.isConnected documentation> | <-US/docs/Web/API/Node.ownerDocument Mozilla Node.ownerDocument documentation> | <-US/docs/Web/API/Node.ownerDocument Mozilla Node.ownerDocument documentation> | <-US/docs/Web/API/Node.ownerDocument Mozilla Node.ownerDocument documentation> | <-US/docs/Web/API/Node.nextSibling Mozilla Node.nextSibling documentation> | <-US/docs/Web/API/Node.nextSibling Mozilla Node.nextSibling documentation> | <-US/docs/Web/API/Node.nextSibling Mozilla Node.nextSibling documentation>
# LANGUAGE PatternSynonyms # # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.Node (getRootNode, getRootNode_, hasChildNodes, hasChildNodes_, normalize, cloneNode, cloneNode_, isEqualNode, isEqualNode_, isSameNode, isSameNode_, compareDocumentPosition, compareDocumentPosition_, contains, contains_, lookupPrefix, lookupPrefix_, lookupPrefixUnsafe, lookupPrefixUnchecked, lookupNamespaceURI, lookupNamespaceURI_, lookupNamespaceURIUnsafe, lookupNamespaceURIUnchecked, isDefaultNamespace, isDefaultNamespace_, insertBefore, insertBefore_, appendChild, appendChild_, replaceChild, replaceChild_, removeChild, removeChild_, pattern ELEMENT_NODE, pattern ATTRIBUTE_NODE, pattern TEXT_NODE, pattern CDATA_SECTION_NODE, pattern ENTITY_REFERENCE_NODE, pattern ENTITY_NODE, pattern PROCESSING_INSTRUCTION_NODE, pattern COMMENT_NODE, pattern DOCUMENT_NODE, pattern DOCUMENT_TYPE_NODE, pattern DOCUMENT_FRAGMENT_NODE, pattern NOTATION_NODE, pattern DOCUMENT_POSITION_DISCONNECTED, pattern DOCUMENT_POSITION_PRECEDING, pattern DOCUMENT_POSITION_FOLLOWING, pattern DOCUMENT_POSITION_CONTAINS, pattern DOCUMENT_POSITION_CONTAINED_BY, pattern DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, getNodeType, getNodeName, getBaseURI, getIsConnected, getOwnerDocument, getOwnerDocumentUnsafe, getOwnerDocumentUnchecked, getParentNode, getParentNodeUnsafe, getParentNodeUnchecked, getParentElement, getParentElementUnsafe, getParentElementUnchecked, getChildNodes, getFirstChild, getFirstChildUnsafe, getFirstChildUnchecked, getLastChild, getLastChildUnsafe, getLastChildUnchecked, getPreviousSibling, getPreviousSiblingUnsafe, getPreviousSiblingUnchecked, getNextSibling, getNextSiblingUnsafe, getNextSiblingUnchecked, setNodeValue, getNodeValue, getNodeValueUnsafe, getNodeValueUnchecked, setTextContent, getTextContent, getTextContentUnsafe, getTextContentUnchecked, Node(..), gTypeNode, IsNode, toNode) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/Node.getRootNode Mozilla Node.getRootNode documentation > getRootNode :: (MonadDOM m, IsNode self) => self -> Maybe GetRootNodeOptions -> m Node getRootNode self options = liftDOM (((toNode self) ^. jsf "getRootNode" [toJSVal options]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.getRootNode Mozilla Node.getRootNode documentation > getRootNode_ :: (MonadDOM m, IsNode self) => self -> Maybe GetRootNodeOptions -> m () getRootNode_ self options = liftDOM (void ((toNode self) ^. jsf "getRootNode" [toJSVal options])) hasChildNodes :: (MonadDOM m, IsNode self) => self -> m Bool hasChildNodes self = liftDOM (((toNode self) ^. jsf "hasChildNodes" ()) >>= valToBool) hasChildNodes_ :: (MonadDOM m, IsNode self) => self -> m () hasChildNodes_ self = liftDOM (void ((toNode self) ^. jsf "hasChildNodes" ())) normalize :: (MonadDOM m, IsNode self) => self -> m () normalize self = liftDOM (void ((toNode self) ^. jsf "normalize" ())) | < Node.cloneNode documentation > cloneNode :: (MonadDOM m, IsNode self) => self -> Bool -> m Node cloneNode self deep = liftDOM (((toNode self) ^. jsf "cloneNode" [toJSVal deep]) >>= fromJSValUnchecked) | < Node.cloneNode documentation > cloneNode_ :: (MonadDOM m, IsNode self) => self -> Bool -> m () cloneNode_ self deep = liftDOM (void ((toNode self) ^. jsf "cloneNode" [toJSVal deep])) | < -US/docs/Web/API/Node.isEqualNode Mozilla documentation > isEqualNode :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m Bool isEqualNode self other = liftDOM (((toNode self) ^. jsf "isEqualNode" [toJSVal other]) >>= valToBool) | < -US/docs/Web/API/Node.isEqualNode Mozilla documentation > isEqualNode_ :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m () isEqualNode_ self other = liftDOM (void ((toNode self) ^. jsf "isEqualNode" [toJSVal other])) | < -US/docs/Web/API/Node.isSameNode Mozilla Node.isSameNode documentation > isSameNode :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m Bool isSameNode self other = liftDOM (((toNode self) ^. jsf "isSameNode" [toJSVal other]) >>= valToBool) | < -US/docs/Web/API/Node.isSameNode Mozilla Node.isSameNode documentation > isSameNode_ :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m () isSameNode_ self other = liftDOM (void ((toNode self) ^. jsf "isSameNode" [toJSVal other])) compareDocumentPosition :: (MonadDOM m, IsNode self, IsNode other) => self -> other -> m Word compareDocumentPosition self other = liftDOM (round <$> (((toNode self) ^. jsf "compareDocumentPosition" [toJSVal other]) >>= valToNumber)) compareDocumentPosition_ :: (MonadDOM m, IsNode self, IsNode other) => self -> other -> m () compareDocumentPosition_ self other = liftDOM (void ((toNode self) ^. jsf "compareDocumentPosition" [toJSVal other])) | < -US/docs/Web/API/Node.contains Mozilla Node.contains documentation > contains :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m Bool contains self other = liftDOM (((toNode self) ^. jsf "contains" [toJSVal other]) >>= valToBool) | < -US/docs/Web/API/Node.contains Mozilla Node.contains documentation > contains_ :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m () contains_ self other = liftDOM (void ((toNode self) ^. jsf "contains" [toJSVal other])) | < -US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation > lookupPrefix :: (MonadDOM m, IsNode self, ToJSString namespaceURI, FromJSString result) => self -> Maybe namespaceURI -> m (Maybe result) lookupPrefix self namespaceURI = liftDOM (((toNode self) ^. jsf "lookupPrefix" [toJSVal namespaceURI]) >>= fromMaybeJSString) | < -US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation > lookupPrefix_ :: (MonadDOM m, IsNode self, ToJSString namespaceURI) => self -> Maybe namespaceURI -> m () lookupPrefix_ self namespaceURI = liftDOM (void ((toNode self) ^. jsf "lookupPrefix" [toJSVal namespaceURI])) | < -US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation > lookupPrefixUnsafe :: (MonadDOM m, IsNode self, ToJSString namespaceURI, HasCallStack, FromJSString result) => self -> Maybe namespaceURI -> m result lookupPrefixUnsafe self namespaceURI = liftDOM ((((toNode self) ^. jsf "lookupPrefix" [toJSVal namespaceURI]) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation > lookupPrefixUnchecked :: (MonadDOM m, IsNode self, ToJSString namespaceURI, FromJSString result) => self -> Maybe namespaceURI -> m result lookupPrefixUnchecked self namespaceURI = liftDOM (((toNode self) ^. jsf "lookupPrefix" [toJSVal namespaceURI]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation > lookupNamespaceURI :: (MonadDOM m, IsNode self, ToJSString prefix, FromJSString result) => self -> Maybe prefix -> m (Maybe result) lookupNamespaceURI self prefix = liftDOM (((toNode self) ^. jsf "lookupNamespaceURI" [toJSVal prefix]) >>= fromMaybeJSString) | < -US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation > lookupNamespaceURI_ :: (MonadDOM m, IsNode self, ToJSString prefix) => self -> Maybe prefix -> m () lookupNamespaceURI_ self prefix = liftDOM (void ((toNode self) ^. jsf "lookupNamespaceURI" [toJSVal prefix])) | < -US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation > lookupNamespaceURIUnsafe :: (MonadDOM m, IsNode self, ToJSString prefix, HasCallStack, FromJSString result) => self -> Maybe prefix -> m result lookupNamespaceURIUnsafe self prefix = liftDOM ((((toNode self) ^. jsf "lookupNamespaceURI" [toJSVal prefix]) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation > lookupNamespaceURIUnchecked :: (MonadDOM m, IsNode self, ToJSString prefix, FromJSString result) => self -> Maybe prefix -> m result lookupNamespaceURIUnchecked self prefix = liftDOM (((toNode self) ^. jsf "lookupNamespaceURI" [toJSVal prefix]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.isDefaultNamespace Mozilla Node.isDefaultNamespace documentation > isDefaultNamespace :: (MonadDOM m, IsNode self, ToJSString namespaceURI) => self -> Maybe namespaceURI -> m Bool isDefaultNamespace self namespaceURI = liftDOM (((toNode self) ^. jsf "isDefaultNamespace" [toJSVal namespaceURI]) >>= valToBool) | < -US/docs/Web/API/Node.isDefaultNamespace Mozilla Node.isDefaultNamespace documentation > isDefaultNamespace_ :: (MonadDOM m, IsNode self, ToJSString namespaceURI) => self -> Maybe namespaceURI -> m () isDefaultNamespace_ self namespaceURI = liftDOM (void ((toNode self) ^. jsf "isDefaultNamespace" [toJSVal namespaceURI])) | < -US/docs/Web/API/Node.insertBefore Mozilla Node.insertBefore documentation > insertBefore :: (MonadDOM m, IsNode self, IsNode node, IsNode child) => self -> node -> Maybe child -> m Node insertBefore self node child = liftDOM (((toNode self) ^. jsf "insertBefore" [toJSVal node, toJSVal child]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.insertBefore Mozilla Node.insertBefore documentation > insertBefore_ :: (MonadDOM m, IsNode self, IsNode node, IsNode child) => self -> node -> Maybe child -> m () insertBefore_ self node child = liftDOM (void ((toNode self) ^. jsf "insertBefore" [toJSVal node, toJSVal child])) | < -US/docs/Web/API/Node.appendChild Mozilla Node.appendChild documentation > appendChild :: (MonadDOM m, IsNode self, IsNode node) => self -> node -> m Node appendChild self node = liftDOM (((toNode self) ^. jsf "appendChild" [toJSVal node]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.appendChild Mozilla Node.appendChild documentation > appendChild_ :: (MonadDOM m, IsNode self, IsNode node) => self -> node -> m () appendChild_ self node = liftDOM (void ((toNode self) ^. jsf "appendChild" [toJSVal node])) | < -US/docs/Web/API/Node.replaceChild Mozilla Node.replaceChild documentation > replaceChild :: (MonadDOM m, IsNode self, IsNode node, IsNode child) => self -> node -> child -> m Node replaceChild self node child = liftDOM (((toNode self) ^. jsf "replaceChild" [toJSVal node, toJSVal child]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.replaceChild Mozilla Node.replaceChild documentation > replaceChild_ :: (MonadDOM m, IsNode self, IsNode node, IsNode child) => self -> node -> child -> m () replaceChild_ self node child = liftDOM (void ((toNode self) ^. jsf "replaceChild" [toJSVal node, toJSVal child])) | < -US/docs/Web/API/Node.removeChild Mozilla Node.removeChild documentation > removeChild :: (MonadDOM m, IsNode self, IsNode child) => self -> child -> m Node removeChild self child = liftDOM (((toNode self) ^. jsf "removeChild" [toJSVal child]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.removeChild Mozilla Node.removeChild documentation > removeChild_ :: (MonadDOM m, IsNode self, IsNode child) => self -> child -> m () removeChild_ self child = liftDOM (void ((toNode self) ^. jsf "removeChild" [toJSVal child])) pattern ELEMENT_NODE = 1 pattern ATTRIBUTE_NODE = 2 pattern TEXT_NODE = 3 pattern CDATA_SECTION_NODE = 4 pattern ENTITY_REFERENCE_NODE = 5 pattern ENTITY_NODE = 6 pattern PROCESSING_INSTRUCTION_NODE = 7 pattern COMMENT_NODE = 8 pattern DOCUMENT_NODE = 9 pattern DOCUMENT_TYPE_NODE = 10 pattern DOCUMENT_FRAGMENT_NODE = 11 pattern NOTATION_NODE = 12 pattern DOCUMENT_POSITION_DISCONNECTED = 1 pattern DOCUMENT_POSITION_PRECEDING = 2 pattern DOCUMENT_POSITION_FOLLOWING = 4 pattern DOCUMENT_POSITION_CONTAINS = 8 pattern DOCUMENT_POSITION_CONTAINED_BY = 16 pattern DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32 | < -US/docs/Web/API/Node.nodeType Mozilla Node.nodeType documentation > getNodeType :: (MonadDOM m, IsNode self) => self -> m Word getNodeType self = liftDOM (round <$> (((toNode self) ^. js "nodeType") >>= valToNumber)) getNodeName :: (MonadDOM m, IsNode self, FromJSString result) => self -> m result getNodeName self = liftDOM (((toNode self) ^. js "nodeName") >>= fromJSValUnchecked) getBaseURI :: (MonadDOM m, IsNode self, FromJSString result) => self -> m result getBaseURI self = liftDOM (((toNode self) ^. js "baseURI") >>= fromJSValUnchecked) getIsConnected :: (MonadDOM m, IsNode self) => self -> m Bool getIsConnected self = liftDOM (((toNode self) ^. js "isConnected") >>= valToBool) getOwnerDocument :: (MonadDOM m, IsNode self) => self -> m (Maybe Document) getOwnerDocument self = liftDOM (((toNode self) ^. js "ownerDocument") >>= fromJSVal) getOwnerDocumentUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Document getOwnerDocumentUnsafe self = liftDOM ((((toNode self) ^. js "ownerDocument") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) getOwnerDocumentUnchecked :: (MonadDOM m, IsNode self) => self -> m Document getOwnerDocumentUnchecked self = liftDOM (((toNode self) ^. js "ownerDocument") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.parentNode Mozilla Node.parentNode documentation > getParentNode :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getParentNode self = liftDOM (((toNode self) ^. js "parentNode") >>= fromJSVal) | < -US/docs/Web/API/Node.parentNode Mozilla Node.parentNode documentation > getParentNodeUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getParentNodeUnsafe self = liftDOM ((((toNode self) ^. js "parentNode") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.parentNode Mozilla Node.parentNode documentation > getParentNodeUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getParentNodeUnchecked self = liftDOM (((toNode self) ^. js "parentNode") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.parentElement Mozilla Node.parentElement documentation > getParentElement :: (MonadDOM m, IsNode self) => self -> m (Maybe Element) getParentElement self = liftDOM (((toNode self) ^. js "parentElement") >>= fromJSVal) | < -US/docs/Web/API/Node.parentElement Mozilla Node.parentElement documentation > getParentElementUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Element getParentElementUnsafe self = liftDOM ((((toNode self) ^. js "parentElement") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.parentElement Mozilla Node.parentElement documentation > getParentElementUnchecked :: (MonadDOM m, IsNode self) => self -> m Element getParentElementUnchecked self = liftDOM (((toNode self) ^. js "parentElement") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.childNodes Mozilla Node.childNodes documentation > getChildNodes :: (MonadDOM m, IsNode self) => self -> m NodeList getChildNodes self = liftDOM (((toNode self) ^. js "childNodes") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.firstChild Mozilla Node.firstChild documentation > getFirstChild :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getFirstChild self = liftDOM (((toNode self) ^. js "firstChild") >>= fromJSVal) | < -US/docs/Web/API/Node.firstChild Mozilla Node.firstChild documentation > getFirstChildUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getFirstChildUnsafe self = liftDOM ((((toNode self) ^. js "firstChild") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.firstChild Mozilla Node.firstChild documentation > getFirstChildUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getFirstChildUnchecked self = liftDOM (((toNode self) ^. js "firstChild") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.lastChild Mozilla Node.lastChild documentation > getLastChild :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getLastChild self = liftDOM (((toNode self) ^. js "lastChild") >>= fromJSVal) | < -US/docs/Web/API/Node.lastChild Mozilla Node.lastChild documentation > getLastChildUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getLastChildUnsafe self = liftDOM ((((toNode self) ^. js "lastChild") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.lastChild Mozilla Node.lastChild documentation > getLastChildUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getLastChildUnchecked self = liftDOM (((toNode self) ^. js "lastChild") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.previousSibling Mozilla Node.previousSibling documentation > getPreviousSibling :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getPreviousSibling self = liftDOM (((toNode self) ^. js "previousSibling") >>= fromJSVal) | < -US/docs/Web/API/Node.previousSibling Mozilla Node.previousSibling documentation > getPreviousSiblingUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getPreviousSiblingUnsafe self = liftDOM ((((toNode self) ^. js "previousSibling") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.previousSibling Mozilla Node.previousSibling documentation > getPreviousSiblingUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getPreviousSiblingUnchecked self = liftDOM (((toNode self) ^. js "previousSibling") >>= fromJSValUnchecked) getNextSibling :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getNextSibling self = liftDOM (((toNode self) ^. js "nextSibling") >>= fromJSVal) getNextSiblingUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getNextSiblingUnsafe self = liftDOM ((((toNode self) ^. js "nextSibling") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) getNextSiblingUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getNextSiblingUnchecked self = liftDOM (((toNode self) ^. js "nextSibling") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation > setNodeValue :: (MonadDOM m, IsNode self, ToJSString val) => self -> Maybe val -> m () setNodeValue self val = liftDOM ((toNode self) ^. jss "nodeValue" (toJSVal val)) | < -US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation > getNodeValue :: (MonadDOM m, IsNode self, FromJSString result) => self -> m (Maybe result) getNodeValue self = liftDOM (((toNode self) ^. js "nodeValue") >>= fromMaybeJSString) | < -US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation > getNodeValueUnsafe :: (MonadDOM m, IsNode self, HasCallStack, FromJSString result) => self -> m result getNodeValueUnsafe self = liftDOM ((((toNode self) ^. js "nodeValue") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation > getNodeValueUnchecked :: (MonadDOM m, IsNode self, FromJSString result) => self -> m result getNodeValueUnchecked self = liftDOM (((toNode self) ^. js "nodeValue") >>= fromJSValUnchecked) | < -US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation > setTextContent :: (MonadDOM m, IsNode self, ToJSString val) => self -> Maybe val -> m () setTextContent self val = liftDOM ((toNode self) ^. jss "textContent" (toJSVal val)) | < -US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation > getTextContent :: (MonadDOM m, IsNode self, FromJSString result) => self -> m (Maybe result) getTextContent self = liftDOM (((toNode self) ^. js "textContent") >>= fromMaybeJSString) | < -US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation > getTextContentUnsafe :: (MonadDOM m, IsNode self, HasCallStack, FromJSString result) => self -> m result getTextContentUnsafe self = liftDOM ((((toNode self) ^. js "textContent") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation > getTextContentUnchecked :: (MonadDOM m, IsNode self, FromJSString result) => self -> m result getTextContentUnchecked self = liftDOM (((toNode self) ^. js "textContent") >>= fromJSValUnchecked)
49935dc80e92a8177df9c01fadb4688ae45211bd6c619fd2693064b794097fb2
gedge-platform/gedge-platform
rabbit_mgmt_wm_health_check_alarms.erl
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %% Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved . %% %% An HTTP API counterpart of 'rabbitmq-diagnostics check_alarms' -module(rabbit_mgmt_wm_health_check_alarms). -export([init/2, to_json/2, content_types_provided/2, is_authorized/2]). -export([resource_exists/2]). -export([variances/2]). -include("rabbit_mgmt.hrl"). -include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl"). %%-------------------------------------------------------------------- init(Req, _State) -> {cowboy_rest, rabbit_mgmt_headers:set_common_permission_headers(Req, ?MODULE), #context{}}. variances(Req, Context) -> {[<<"accept-encoding">>, <<"origin">>], Req, Context}. content_types_provided(ReqData, Context) -> {rabbit_mgmt_util:responder_map(to_json), ReqData, Context}. resource_exists(ReqData, Context) -> {true, ReqData, Context}. to_json(ReqData, Context) -> Timeout = case cowboy_req:header(<<"timeout">>, ReqData) of undefined -> 70000; Val -> list_to_integer(binary_to_list(Val)) end, case rabbit_alarm:get_alarms(Timeout) of [] -> rabbit_mgmt_util:reply([{status, ok}], ReqData, Context); Xs when length(Xs) > 0 -> Msg = "There are alarms in effect in the cluster", failure(Msg, Xs, ReqData, Context) end. failure(Message, Alarms0, ReqData, Context) -> Alarms = rabbit_alarm:format_as_maps(Alarms0), Body = #{ status => failed, reason => rabbit_data_coercion:to_binary(Message), alarms => Alarms }, {Response, ReqData1, Context1} = rabbit_mgmt_util:reply(Body, ReqData, Context), {stop, cowboy_req:reply(?HEALTH_CHECK_FAILURE_STATUS, #{}, Response, ReqData1), Context1}. is_authorized(ReqData, Context) -> rabbit_mgmt_util:is_authorized(ReqData, Context).
null
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbitmq_management/src/rabbit_mgmt_wm_health_check_alarms.erl
erlang
An HTTP API counterpart of 'rabbitmq-diagnostics check_alarms' --------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved . -module(rabbit_mgmt_wm_health_check_alarms). -export([init/2, to_json/2, content_types_provided/2, is_authorized/2]). -export([resource_exists/2]). -export([variances/2]). -include("rabbit_mgmt.hrl"). -include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl"). init(Req, _State) -> {cowboy_rest, rabbit_mgmt_headers:set_common_permission_headers(Req, ?MODULE), #context{}}. variances(Req, Context) -> {[<<"accept-encoding">>, <<"origin">>], Req, Context}. content_types_provided(ReqData, Context) -> {rabbit_mgmt_util:responder_map(to_json), ReqData, Context}. resource_exists(ReqData, Context) -> {true, ReqData, Context}. to_json(ReqData, Context) -> Timeout = case cowboy_req:header(<<"timeout">>, ReqData) of undefined -> 70000; Val -> list_to_integer(binary_to_list(Val)) end, case rabbit_alarm:get_alarms(Timeout) of [] -> rabbit_mgmt_util:reply([{status, ok}], ReqData, Context); Xs when length(Xs) > 0 -> Msg = "There are alarms in effect in the cluster", failure(Msg, Xs, ReqData, Context) end. failure(Message, Alarms0, ReqData, Context) -> Alarms = rabbit_alarm:format_as_maps(Alarms0), Body = #{ status => failed, reason => rabbit_data_coercion:to_binary(Message), alarms => Alarms }, {Response, ReqData1, Context1} = rabbit_mgmt_util:reply(Body, ReqData, Context), {stop, cowboy_req:reply(?HEALTH_CHECK_FAILURE_STATUS, #{}, Response, ReqData1), Context1}. is_authorized(ReqData, Context) -> rabbit_mgmt_util:is_authorized(ReqData, Context).
2f5233fbfe4fa9f9a3be98fa74dd0946088cf88e6c20539412aca9f5c97d7f24
eareese/htdp-exercises
160-set-add.rkt
#lang htdp/bsl Exercise 160 . Design the functions set+.L and set+.R , which create a set by adding a number x to some given set s for the left - hand and right - hand data definition , respectively . A Son . L is one of : ; – empty – ( cons Number Son . L ) ; ; Son is used when it ; applies to Son.L and Son.R ; A Son.R is one of: ; – empty – ( cons Number Son . R ) ; ; Constraint If s is a Son.R, ; no number occurs twice in s. Figure 58 : Two data representations for sets ; Son ;; empty set (define es '()) ; Number Son -> Son ; is x in s (define (in? x s) (member? x s)) Figure 59 : Functions for the two data representations of sets ; Number Son.L -> Son.L ; remove x from s (define s1.L (cons 1 (cons 1 '()))) (check-expect (set-.L 1 s1.L) es) (define (set-.L x s) (remove-all x s)) ; Number Son.R -> Son.R ; remove x from s (define s1.R (cons 1 '())) (check-expect (set-.R 1 s1.R) es) (define (set-.R x s) (remove x s)) (define ASET (cons 1 (cons 2 '()))) ; Number Son.L -> Son.L ; add x to s (check-expect (set+.L 2 ASET) (cons 2 (cons 1 (cons 2 '())))) (define (set+.L x s) (append (cons x '()) s)) ; Number Son.R -> Son.R ; add x to s (check-expect (set+.R 2 ASET) (cons 1 (cons 2 '()))) ; set is unique (check-expect (set+.R 3 ASET) (cons 3 (cons 1 (cons 2 '())))) (define (set+.R x s) (if (member? x s) s (append (cons x '()) s)))
null
https://raw.githubusercontent.com/eareese/htdp-exercises/a85ff3111d459dda0e94d9b463d01a09accbf9bf/part02-arbitrarily-large-data/160-set-add.rkt
racket
– empty Son is used when it applies to Son.L and Son.R A Son.R is one of: – empty Constraint If s is a Son.R, no number occurs twice in s. Son empty set Number Son -> Son is x in s Number Son.L -> Son.L remove x from s Number Son.R -> Son.R remove x from s Number Son.L -> Son.L add x to s Number Son.R -> Son.R add x to s set is unique
#lang htdp/bsl Exercise 160 . Design the functions set+.L and set+.R , which create a set by adding a number x to some given set s for the left - hand and right - hand data definition , respectively . A Son . L is one of : – ( cons Number Son . L ) – ( cons Number Son . R ) Figure 58 : Two data representations for sets (define es '()) (define (in? x s) (member? x s)) Figure 59 : Functions for the two data representations of sets (define s1.L (cons 1 (cons 1 '()))) (check-expect (set-.L 1 s1.L) es) (define (set-.L x s) (remove-all x s)) (define s1.R (cons 1 '())) (check-expect (set-.R 1 s1.R) es) (define (set-.R x s) (remove x s)) (define ASET (cons 1 (cons 2 '()))) (check-expect (set+.L 2 ASET) (cons 2 (cons 1 (cons 2 '())))) (define (set+.L x s) (append (cons x '()) s)) (check-expect (set+.R 3 ASET) (cons 3 (cons 1 (cons 2 '())))) (define (set+.R x s) (if (member? x s) s (append (cons x '()) s)))
89d043a3eb6ef48e1dcbda39b068cc1db6adeadd028e959ab34fba8575d1d799
diku-dk/futhark
Engine.hs
{-# LANGUAGE Strict #-} # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # -- | -- -- Perform general rule-based simplification based on data dependency -- information. This module will: -- * Perform common - subexpression elimination ( CSE ) . -- -- * Hoist expressions out of loops (including lambdas) and -- branches. This is done as aggressively as possible. -- -- * Apply simplification rules (see " Futhark . Optimise . Simplification . Rules " ) . -- -- If you just want to run the simplifier as simply as possible, you may prefer to use the " Futhark . Optimise . Simplify " module . module Futhark.Optimise.Simplify.Engine * Monadic interface SimpleM, runSimpleM, SimpleOps (..), SimplifyOp, bindableSimpleOps, Env (envHoistBlockers, envRules), emptyEnv, HoistBlockers (..), neverBlocks, noExtraHoistBlockers, neverHoist, BlockPred, orIf, hasFree, isConsumed, isConsuming, isFalse, isOp, isNotSafe, isDeviceMigrated, asksEngineEnv, askVtable, localVtable, -- * Building blocks SimplifiableRep, Simplifiable (..), simplifyFun, simplifyStms, simplifyStmsWithUsage, simplifyLambda, simplifyLambdaNoHoisting, bindLParams, simplifyBody, ST.SymbolTable, hoistStms, blockIf, blockMigrated, enterLoop, constructBody, module Futhark.Optimise.Simplify.Rep, ) where import Control.Monad.Reader import Control.Monad.State.Strict import Data.Either import Data.List (find, foldl', inits, mapAccumL) import Data.Map qualified as M import Data.Maybe import Futhark.Analysis.SymbolTable qualified as ST import Futhark.Analysis.UsageTable qualified as UT import Futhark.Construct import Futhark.IR import Futhark.IR.Prop.Aliases import Futhark.Optimise.Simplify.Rep import Futhark.Optimise.Simplify.Rule import Futhark.Util (nubOrd) data HoistBlockers rep = HoistBlockers { -- | Blocker for hoisting out of parallel loops. blockHoistPar :: BlockPred (Wise rep), -- | Blocker for hoisting out of sequential loops. blockHoistSeq :: BlockPred (Wise rep), -- | Blocker for hoisting out of branches. blockHoistBranch :: BlockPred (Wise rep), isAllocation :: Stm (Wise rep) -> Bool } noExtraHoistBlockers :: HoistBlockers rep noExtraHoistBlockers = HoistBlockers neverBlocks neverBlocks neverBlocks (const False) neverHoist :: HoistBlockers rep neverHoist = HoistBlockers alwaysBlocks alwaysBlocks alwaysBlocks (const False) data Env rep = Env { envRules :: RuleBook (Wise rep), envHoistBlockers :: HoistBlockers rep, envVtable :: ST.SymbolTable (Wise rep) } emptyEnv :: RuleBook (Wise rep) -> HoistBlockers rep -> Env rep emptyEnv rules blockers = Env { envRules = rules, envHoistBlockers = blockers, envVtable = mempty } -- | A function that protects a hoisted operation (if possible). The first operand is the condition of the ' Case ' we have hoisted out of -- (or equivalently, a boolean indicating whether a loop has nonzero -- trip count). type Protect m = SubExp -> Pat (LetDec (Rep m)) -> Op (Rep m) -> Maybe (m ()) type SimplifyOp rep op = op -> SimpleM rep (op, Stms (Wise rep)) data SimpleOps rep = SimpleOps { mkExpDecS :: ST.SymbolTable (Wise rep) -> Pat (LetDec (Wise rep)) -> Exp (Wise rep) -> SimpleM rep (ExpDec (Wise rep)), mkBodyS :: ST.SymbolTable (Wise rep) -> Stms (Wise rep) -> Result -> SimpleM rep (Body (Wise rep)), | Make a hoisted Op safe . The SubExp is a boolean -- that is true when the value of the statement will -- actually be used. protectHoistedOpS :: Protect (Builder (Wise rep)), opUsageS :: Op (Wise rep) -> UT.UsageTable, simplifyPatFromExpS :: Pat (LetDec rep) -> Exp (Wise rep) -> SimpleM rep (Pat (LetDec rep)), simplifyOpS :: SimplifyOp rep (Op (Wise rep)) } bindableSimpleOps :: (SimplifiableRep rep, Buildable rep) => SimplifyOp rep (Op (Wise rep)) -> SimpleOps rep bindableSimpleOps = SimpleOps mkExpDecS' mkBodyS' protectHoistedOpS' (const mempty) simplifyPatFromExp where mkExpDecS' _ pat e = pure $ mkExpDec pat e mkBodyS' _ stms res = pure $ mkBody stms res protectHoistedOpS' _ _ _ = Nothing simplifyPatFromExp pat _ = traverse simplify pat newtype SimpleM rep a = SimpleM ( ReaderT (SimpleOps rep, Env rep) (State (VNameSource, Bool, Certs)) a ) deriving ( Applicative, Functor, Monad, MonadReader (SimpleOps rep, Env rep), MonadState (VNameSource, Bool, Certs) ) instance MonadFreshNames (SimpleM rep) where putNameSource src = modify $ \(_, b, c) -> (src, b, c) getNameSource = gets $ \(a, _, _) -> a instance SimplifiableRep rep => HasScope (Wise rep) (SimpleM rep) where askScope = ST.toScope <$> askVtable lookupType name = do vtable <- askVtable case ST.lookupType name vtable of Just t -> pure t Nothing -> error $ "SimpleM.lookupType: cannot find variable " ++ prettyString name ++ " in symbol table." instance SimplifiableRep rep => LocalScope (Wise rep) (SimpleM rep) where localScope types = localVtable (<> ST.fromScope types) runSimpleM :: SimpleM rep a -> SimpleOps rep -> Env rep -> VNameSource -> ((a, Bool), VNameSource) runSimpleM (SimpleM m) simpl env src = let (x, (src', b, _)) = runState (runReaderT m (simpl, env)) (src, False, mempty) in ((x, b), src') askEngineEnv :: SimpleM rep (Env rep) askEngineEnv = asks snd asksEngineEnv :: (Env rep -> a) -> SimpleM rep a asksEngineEnv f = f <$> askEngineEnv askVtable :: SimpleM rep (ST.SymbolTable (Wise rep)) askVtable = asksEngineEnv envVtable localVtable :: (ST.SymbolTable (Wise rep) -> ST.SymbolTable (Wise rep)) -> SimpleM rep a -> SimpleM rep a localVtable f = local $ \(ops, env) -> (ops, env {envVtable = f $ envVtable env}) collectCerts :: SimpleM rep a -> SimpleM rep (a, Certs) collectCerts m = do x <- m (a, b, cs) <- get put (a, b, mempty) pure (x, cs) | that we have changed something and it would be a good idea -- to re-run the simplifier. changed :: SimpleM rep () changed = modify $ \(src, _, cs) -> (src, True, cs) usedCerts :: Certs -> SimpleM rep () usedCerts cs = modify $ \(a, b, c) -> (a, b, cs <> c) -- | Indicate in the symbol table that we have descended into a loop. enterLoop :: SimpleM rep a -> SimpleM rep a enterLoop = localVtable ST.deepen bindFParams :: SimplifiableRep rep => [FParam (Wise rep)] -> SimpleM rep a -> SimpleM rep a bindFParams params = localVtable $ ST.insertFParams params bindLParams :: SimplifiableRep rep => [LParam (Wise rep)] -> SimpleM rep a -> SimpleM rep a bindLParams params = localVtable $ \vtable -> foldr ST.insertLParam vtable params bindArrayLParams :: SimplifiableRep rep => [LParam (Wise rep)] -> SimpleM rep a -> SimpleM rep a bindArrayLParams params = localVtable $ \vtable -> foldl' (flip ST.insertLParam) vtable params bindMerge :: SimplifiableRep rep => [(FParam (Wise rep), SubExp, SubExpRes)] -> SimpleM rep a -> SimpleM rep a bindMerge = localVtable . ST.insertLoopMerge bindLoopVar :: SimplifiableRep rep => VName -> IntType -> SubExp -> SimpleM rep a -> SimpleM rep a bindLoopVar var it bound = localVtable $ ST.insertLoopVar var it bound makeSafe :: Exp rep -> Maybe (Exp rep) makeSafe (BasicOp (BinOp (SDiv t _) x y)) = Just $ BasicOp (BinOp (SDiv t Safe) x y) makeSafe (BasicOp (BinOp (SDivUp t _) x y)) = Just $ BasicOp (BinOp (SDivUp t Safe) x y) makeSafe (BasicOp (BinOp (SQuot t _) x y)) = Just $ BasicOp (BinOp (SQuot t Safe) x y) makeSafe (BasicOp (BinOp (UDiv t _) x y)) = Just $ BasicOp (BinOp (UDiv t Safe) x y) makeSafe (BasicOp (BinOp (UDivUp t _) x y)) = Just $ BasicOp (BinOp (UDivUp t Safe) x y) makeSafe (BasicOp (BinOp (SMod t _) x y)) = Just $ BasicOp (BinOp (SMod t Safe) x y) makeSafe (BasicOp (BinOp (SRem t _) x y)) = Just $ BasicOp (BinOp (SRem t Safe) x y) makeSafe (BasicOp (BinOp (UMod t _) x y)) = Just $ BasicOp (BinOp (UMod t Safe) x y) makeSafe _ = Nothing emptyOfType :: MonadBuilder m => [VName] -> Type -> m (Exp (Rep m)) emptyOfType _ Mem {} = error "emptyOfType: Cannot hoist non-existential memory." emptyOfType _ Acc {} = error "emptyOfType: Cannot hoist accumulator." emptyOfType _ (Prim pt) = pure $ BasicOp $ SubExp $ Constant $ blankPrimValue pt emptyOfType ctx_names (Array et shape _) = do let dims = map zeroIfContext $ shapeDims shape pure $ BasicOp $ Scratch et dims where zeroIfContext (Var v) | v `elem` ctx_names = intConst Int64 0 zeroIfContext se = se protectIf :: MonadBuilder m => Protect m -> (Exp (Rep m) -> Bool) -> SubExp -> Stm (Rep m) -> m () protectIf _ _ taken (Let pat aux (Match [cond] [Case [Just (BoolValue True)] taken_body] untaken_body (MatchDec if_ts MatchFallback))) = do cond' <- letSubExp "protect_cond_conj" $ BasicOp $ BinOp LogAnd taken cond auxing aux . letBind pat $ Match [cond'] [Case [Just (BoolValue True)] taken_body] untaken_body $ MatchDec if_ts MatchFallback protectIf _ _ taken (Let pat aux (BasicOp (Assert cond msg loc))) = do not_taken <- letSubExp "loop_not_taken" $ BasicOp $ UnOp Not taken cond' <- letSubExp "protect_assert_disj" $ BasicOp $ BinOp LogOr not_taken cond auxing aux $ letBind pat $ BasicOp $ Assert cond' msg loc protectIf protect _ taken (Let pat aux (Op op)) | Just m <- protect taken pat op = auxing aux m protectIf _ f taken (Let pat aux e) | f e = case makeSafe e of Just e' -> auxing aux $ letBind pat e' Nothing -> do taken_body <- eBody [pure e] untaken_body <- eBody $ map (emptyOfType $ patNames pat) (patTypes pat) if_ts <- expTypesFromPat pat auxing aux . letBind pat $ Match [taken] [Case [Just $ BoolValue True] taken_body] untaken_body $ MatchDec if_ts MatchFallback protectIf _ _ _ stm = addStm stm -- | We are willing to hoist potentially unsafe statements out of -- loops, but they must be protected by adding a branch on top of -- them. protectLoopHoisted :: SimplifiableRep rep => [(FParam (Wise rep), SubExp)] -> LoopForm (Wise rep) -> SimpleM rep (a, b, Stms (Wise rep)) -> SimpleM rep (a, b, Stms (Wise rep)) protectLoopHoisted merge form m = do (x, y, stms) <- m ops <- asks $ protectHoistedOpS . fst stms' <- runBuilder_ $ do if not $ all (safeExp . stmExp) stms then do is_nonempty <- checkIfNonEmpty mapM_ (protectIf ops (not . safeExp) is_nonempty) stms else addStms stms pure (x, y, stms') where checkIfNonEmpty = case form of WhileLoop cond | Just (_, cond_init) <- find ((== cond) . paramName . fst) merge -> pure cond_init | otherwise -> pure $ constant True -- infinite loop ForLoop _ it bound _ -> letSubExp "loop_nonempty" $ BasicOp $ CmpOp (CmpSlt it) (intConst it 0) bound -- Produces a true subexpression if the pattern (as in a 'Case') -- matches the subexpression. matching :: BuilderOps rep => [(SubExp, Maybe PrimValue)] -> Builder rep SubExp matching = letSubExp "match" <=< eAll <=< sequence . mapMaybe cmp where cmp (se, Just (BoolValue True)) = Just $ pure se cmp (se, Just v) = Just . letSubExp "match_val" . BasicOp $ CmpOp (CmpEq (primValueType v)) se (Constant v) cmp (_, Nothing) = Nothing matchingExactlyThis :: BuilderOps rep => [SubExp] -> [[Maybe PrimValue]] -> [Maybe PrimValue] -> Builder rep SubExp matchingExactlyThis ses prior this = do prior_matches <- mapM (matching . zip ses) prior letSubExp "matching_just_this" =<< eBinOp LogAnd (eUnOp Not (eAny prior_matches)) (eSubExp =<< matching (zip ses this)) -- | We are willing to hoist potentially unsafe statements out of -- matches, but they must be protected by adding a branch on top of -- them. (This means such hoisting is not worth it unless they are in -- turn hoisted out of a loop somewhere.) protectCaseHoisted :: SimplifiableRep rep => -- | Scrutinee. [SubExp] -> | Pattern of previosu cases . [[Maybe PrimValue]] -> -- | Pattern of this case. [Maybe PrimValue] -> SimpleM rep (Stms (Wise rep), a) -> SimpleM rep (Stms (Wise rep), a) protectCaseHoisted ses prior vs m = do (hoisted, x) <- m ops <- asks $ protectHoistedOpS . fst hoisted' <- runBuilder_ $ do if not $ all (safeExp . stmExp) hoisted then do cond' <- matchingExactlyThis ses prior vs mapM_ (protectIf ops unsafeOrCostly cond') hoisted else addStms hoisted pure (hoisted', x) where unsafeOrCostly e = not (safeExp e) || not (cheapExp e) -- | Statements that are not worth hoisting out of loops, because they -- are unsafe, and added safety (by 'protectLoopHoisted') may inhibit -- further optimisation. notWorthHoisting :: ASTRep rep => BlockPred rep notWorthHoisting _ _ (Let pat _ e) = not (safeExp e) && any ((> 0) . arrayRank) (patTypes pat) -- Top-down simplify a statement (including copy propagation into the -- pattern and such). Does not recurse into any sub-Bodies or Ops. nonrecSimplifyStm :: SimplifiableRep rep => Stm (Wise rep) -> SimpleM rep (Stm (Wise rep)) nonrecSimplifyStm (Let pat (StmAux cs attrs (_, dec)) e) = do cs' <- simplify cs e' <- simplifyExpBase e simplifyPat <- asks $ simplifyPatFromExpS . fst (pat', pat_cs) <- collectCerts $ simplifyPat (removePatWisdom pat) e' let aux' = StmAux (cs' <> pat_cs) attrs dec pure $ mkWiseStm pat' aux' e' Bottom - up simplify a statement . Recurses into sub - Bodies and Ops . -- Does not copy-propagate into the pattern and similar, as it is -- assumed 'nonrecSimplifyStm' has already touched it (and worst case, -- it'll get it on the next round of the overall fixpoint iteration.) recSimplifyStm :: SimplifiableRep rep => Stm (Wise rep) -> UT.UsageTable -> SimpleM rep (Stms (Wise rep), Stm (Wise rep)) recSimplifyStm (Let pat (StmAux cs attrs (_, dec)) e) usage = do ((e', e_hoisted), e_cs) <- collectCerts $ simplifyExp (usage <> UT.usageInPat pat) pat e let aux' = StmAux (cs <> e_cs) attrs dec pure (e_hoisted, mkWiseStm (removePatWisdom pat) aux' e') hoistStms :: SimplifiableRep rep => RuleBook (Wise rep) -> BlockPred (Wise rep) -> Stms (Wise rep) -> SimpleM rep (a, UT.UsageTable) -> SimpleM rep (a, Stms (Wise rep), Stms (Wise rep)) hoistStms rules block orig_stms final = do (a, blocked, hoisted) <- simplifyStmsBottomUp orig_stms unless (null hoisted) changed pure (a, stmsFromList blocked, stmsFromList hoisted) where simplifyStmsBottomUp stms = do opUsage <- asks $ opUsageS . fst let usageInStm stm = UT.usageInStm stm <> case stmExp stm of Op op -> opUsage op _ -> mempty (x, _, stms') <- hoistableStms usageInStm stms -- We need to do a final pass to ensure that nothing is -- hoisted past something that it depends on. let (blocked, hoisted) = partitionEithers $ blockUnhoistedDeps stms' pure (x, blocked, hoisted) descend usageInStm stms m = case stmsHead stms of Nothing -> m Just (stms_h, stms_t) -> localVtable (ST.insertStm stms_h) $ do (x, usage, stms_t') <- descend usageInStm stms_t m process usageInStm stms_h stms_t' usage x process usageInStm stm stms usage x = do vtable <- askVtable res <- bottomUpSimplifyStm rules (vtable, usage) stm case res of Nothing -- Nothing to optimise - see if hoistable. | block vtable usage stm -> -- No, not hoistable. pure ( x, expandUsage usageInStm vtable usage stm `UT.without` provides stm, Left stm : stms ) | otherwise -> Yes , . pure ( x, expandUsage usageInStm vtable usage stm, Right stm : stms ) Just optimstms -> do changed descend usageInStm optimstms $ pure (x, usage, stms) hoistableStms usageInStm stms = case stmsHead stms of Nothing -> do (x, usage) <- final pure (x, usage, mempty) Just (stms_h, stms_t) -> do stms_h' <- nonrecSimplifyStm stms_h vtable <- askVtable simplified <- topDownSimplifyStm rules vtable stms_h' case simplified of Just newstms -> do changed hoistableStms usageInStm (newstms <> stms_t) Nothing -> do (x, usage, stms_t') <- localVtable (ST.insertStm stms_h') $ hoistableStms usageInStm stms_t if not $ any (`UT.isUsedDirectly` usage) $ provides stms_h' then -- Dead statement. pure (x, usage, stms_t') else do (stms_h_stms, stms_h'') <- recSimplifyStm stms_h' usage descend usageInStm stms_h_stms $ process usageInStm stms_h'' stms_t' usage x blockUnhoistedDeps :: ASTRep rep => [Either (Stm rep) (Stm rep)] -> [Either (Stm rep) (Stm rep)] blockUnhoistedDeps = snd . mapAccumL block mempty where block blocked (Left need) = (blocked <> namesFromList (provides need), Left need) block blocked (Right need) | blocked `namesIntersect` freeIn need = (blocked <> namesFromList (provides need), Left need) | otherwise = (blocked, Right need) provides :: Stm rep -> [VName] provides = patNames . stmPat expandUsage :: Aliased rep => (Stm rep -> UT.UsageTable) -> ST.SymbolTable rep -> UT.UsageTable -> Stm rep -> UT.UsageTable expandUsage usageInStm vtable utable stm@(Let pat aux e) = stmUsages <> utable where stmUsages = UT.expand (`ST.lookupAliases` vtable) (usageInStm stm <> usageThroughAliases) <> ( if any (`UT.isSize` utable) (patNames pat) then UT.sizeUsages (freeIn (stmAuxCerts aux) <> freeIn e) else mempty ) usageThroughAliases = mconcat . mapMaybe usageThroughBindeeAliases $ zip (patNames pat) (patAliases pat) usageThroughBindeeAliases (name, aliases) = do uses <- UT.lookup name utable pure . mconcat $ map (`UT.usage` (uses `UT.withoutU` UT.presentU)) $ namesToList aliases type BlockPred rep = ST.SymbolTable rep -> UT.UsageTable -> Stm rep -> Bool neverBlocks :: BlockPred rep neverBlocks _ _ _ = False alwaysBlocks :: BlockPred rep alwaysBlocks _ _ _ = True isFalse :: Bool -> BlockPred rep isFalse b _ _ _ = not b orIf :: BlockPred rep -> BlockPred rep -> BlockPred rep orIf p1 p2 body vtable need = p1 body vtable need || p2 body vtable need andAlso :: BlockPred rep -> BlockPred rep -> BlockPred rep andAlso p1 p2 body vtable need = p1 body vtable need && p2 body vtable need isConsumed :: BlockPred rep isConsumed _ utable = any (`UT.isConsumed` utable) . patNames . stmPat isOp :: BlockPred rep isOp _ _ (Let _ _ Op {}) = True isOp _ _ _ = False constructBody :: SimplifiableRep rep => Stms (Wise rep) -> Result -> SimpleM rep (Body (Wise rep)) constructBody stms res = fmap fst . runBuilder . buildBody_ $ do addStms stms pure res blockIf :: SimplifiableRep rep => BlockPred (Wise rep) -> Stms (Wise rep) -> SimpleM rep (a, UT.UsageTable) -> SimpleM rep (a, Stms (Wise rep), Stms (Wise rep)) blockIf block stms m = do rules <- asksEngineEnv envRules hoistStms rules block stms m hasFree :: ASTRep rep => Names -> BlockPred rep hasFree ks _ _ need = ks `namesIntersect` freeIn need isNotSafe :: ASTRep rep => BlockPred rep isNotSafe _ _ = not . safeExp . stmExp isConsuming :: Aliased rep => BlockPred rep isConsuming _ _ = isUpdate . stmExp where isUpdate e = consumedInExp e /= mempty isNotCheap :: ASTRep rep => BlockPred rep isNotCheap _ _ = not . cheapStm cheapStm :: ASTRep rep => Stm rep -> Bool cheapStm = cheapExp . stmExp cheapExp :: ASTRep rep => Exp rep -> Bool cheapExp (BasicOp BinOp {}) = True cheapExp (BasicOp SubExp {}) = True cheapExp (BasicOp UnOp {}) = True cheapExp (BasicOp CmpOp {}) = True cheapExp (BasicOp ConvOp {}) = True cheapExp (BasicOp Assert {}) = True cheapExp (BasicOp Copy {}) = False cheapExp (BasicOp Replicate {}) = False cheapExp (BasicOp Concat {}) = False cheapExp (BasicOp Manifest {}) = False cheapExp DoLoop {} = False cheapExp (Match _ cases defbranch _) = all (all cheapStm . bodyStms . caseBody) cases && all cheapStm (bodyStms defbranch) cheapExp (Op op) = cheapOp op cheapExp _ = True -- Used to be False, but -- let's try it out. loopInvariantStm :: ASTRep rep => ST.SymbolTable rep -> Stm rep -> Bool loopInvariantStm vtable = all (`nameIn` ST.availableAtClosestLoop vtable) . namesToList . freeIn matchBlocker :: SimplifiableRep rep => [SubExp] -> MatchDec rt -> SimpleM rep (BlockPred (Wise rep)) matchBlocker cond (MatchDec _ ifsort) = do is_alloc_fun <- asksEngineEnv $ isAllocation . envHoistBlockers branch_blocker <- asksEngineEnv $ blockHoistBranch . envHoistBlockers vtable <- askVtable let -- We are unwilling to hoist things that are unsafe or costly, -- except if they are invariant to the most enclosing loop, -- because in that case they will also be hoisted past that -- loop. -- -- We also try very hard to hoist allocations or anything that -- contributes to memory or array size, because that will allow -- allocations to be hoisted. cond_loop_invariant = all (`nameIn` ST.availableAtClosestLoop vtable) $ namesToList $ freeIn cond desirableToHoist usage stm = is_alloc_fun stm || ( ST.loopDepth vtable > 0 && cond_loop_invariant && ifsort /= MatchFallback && loopInvariantStm vtable stm -- Avoid hoisting out something that might change the -- asymptotics of the program. && all primType (patTypes (stmPat stm)) ) || ( ifsort /= MatchFallback && any (`UT.isSize` usage) (patNames (stmPat stm)) && all primType (patTypes (stmPat stm)) ) notDesirableToHoist _ usage stm = not $ desirableToHoist usage stm No matter what , we always want to hoist constants as much as -- possible. isNotHoistableBnd _ _ (Let _ _ (BasicOp ArrayLit {})) = False isNotHoistableBnd _ _ (Let _ _ (BasicOp SubExp {})) = False -- Hoist things that are free. isNotHoistableBnd _ _ (Let _ _ (BasicOp Reshape {})) = False isNotHoistableBnd _ _ (Let _ _ (BasicOp Rearrange {})) = False isNotHoistableBnd _ _ (Let _ _ (BasicOp Rotate {})) = False isNotHoistableBnd _ _ (Let _ _ (BasicOp (Index _ slice))) = null $ sliceDims slice -- isNotHoistableBnd _ _ stm | is_alloc_fun stm = False isNotHoistableBnd _ _ _ = -- Hoist aggressively out of versioning branches. ifsort /= MatchEquiv block = branch_blocker `orIf` ( (isNotSafe `orIf` isNotCheap `orIf` isNotHoistableBnd) `andAlso` notDesirableToHoist ) `orIf` isConsuming pure block -- | Simplify a single body. simplifyBody :: SimplifiableRep rep => BlockPred (Wise rep) -> UT.UsageTable -> [UT.Usages] -> Body (Wise rep) -> SimpleM rep (Stms (Wise rep), Body (Wise rep)) simplifyBody blocker usage res_usages (Body _ stms res) = do (res', stms', hoisted) <- blockIf blocker stms $ do (res', res_usage) <- simplifyResult res_usages res pure (res', res_usage <> usage) body' <- constructBody stms' res' pure (hoisted, body') -- | Simplify a single body. simplifyBodyNoHoisting :: SimplifiableRep rep => UT.UsageTable -> [UT.Usages] -> Body (Wise rep) -> SimpleM rep (Body (Wise rep)) simplifyBodyNoHoisting usage res_usages body = snd <$> simplifyBody (isFalse False) usage res_usages body usageFromDiet :: Diet -> UT.Usages usageFromDiet Consume = UT.consumedU usageFromDiet _ = mempty -- | Simplify a single 'Result'. simplifyResult :: SimplifiableRep rep => [UT.Usages] -> Result -> SimpleM rep (Result, UT.UsageTable) simplifyResult usages res = do res' <- mapM simplify res vtable <- askVtable let more_usages = mconcat $ do (u, Var v) <- zip usages $ map resSubExp res let als_usages = map (`UT.usage` (u `UT.withoutU` UT.presentU)) (namesToList (ST.lookupAliases v vtable)) UT.usage v u : als_usages pure ( res', UT.usages (freeIn res') <> foldMap UT.inResultUsage (namesToList (freeIn res')) <> more_usages ) isDoLoopResult :: Result -> UT.UsageTable isDoLoopResult = mconcat . map checkForVar where checkForVar (SubExpRes _ (Var ident)) = UT.inResultUsage ident checkForVar _ = mempty simplifyStms :: SimplifiableRep rep => Stms (Wise rep) -> SimpleM rep (Stms (Wise rep)) simplifyStms stms = do simplifyStmsWithUsage all_used stms where all_used = UT.usages (namesFromList (M.keys (scopeOf stms))) simplifyStmsWithUsage :: SimplifiableRep rep => UT.UsageTable -> Stms (Wise rep) -> SimpleM rep (Stms (Wise rep)) simplifyStmsWithUsage usage stms = do ((), stms', _) <- blockIf (isFalse False) stms $ pure ((), usage) pure stms' simplifyOp :: Op (Wise rep) -> SimpleM rep (Op (Wise rep), Stms (Wise rep)) simplifyOp op = do f <- asks $ simplifyOpS . fst f op simplifyExp :: SimplifiableRep rep => UT.UsageTable -> Pat (LetDec (Wise rep)) -> Exp (Wise rep) -> SimpleM rep (Exp (Wise rep), Stms (Wise rep)) simplifyExp usage (Pat pes) (Match ses cases defbody ifdec@(MatchDec ts ifsort)) = do let pes_usages = map (fromMaybe mempty . (`UT.lookup` usage) . patElemName) pes ses' <- mapM simplify ses ts' <- mapM simplify ts let pats = map casePat cases block <- matchBlocker ses ifdec (cases_hoisted, cases') <- unzip <$> zipWithM (simplifyCase block ses' pes_usages) (inits pats) cases (defbody_hoisted, defbody') <- protectCaseHoisted ses' pats [] $ simplifyBody block usage pes_usages defbody pure ( Match ses' cases' defbody' $ MatchDec ts' ifsort, mconcat $ defbody_hoisted : cases_hoisted ) where simplifyCase block ses' pes_usages prior (Case vs body) = do (hoisted, body') <- protectCaseHoisted ses' prior vs $ simplifyBody block usage pes_usages body pure (hoisted, Case vs body') simplifyExp _ _ (DoLoop merge form loopbody) = do let (params, args) = unzip merge params' <- mapM (traverse simplify) params args' <- mapM simplify args let merge' = zip params' args' (form', boundnames, wrapbody) <- case form of ForLoop loopvar it boundexp loopvars -> do boundexp' <- simplify boundexp let (loop_params, loop_arrs) = unzip loopvars loop_params' <- mapM (traverse simplify) loop_params loop_arrs' <- mapM simplify loop_arrs let form' = ForLoop loopvar it boundexp' (zip loop_params' loop_arrs') pure ( form', namesFromList (loopvar : map paramName loop_params') <> fparamnames, bindLoopVar loopvar it boundexp' . protectLoopHoisted merge' form' . bindArrayLParams loop_params' ) WhileLoop cond -> do cond' <- simplify cond pure ( WhileLoop cond', fparamnames, protectLoopHoisted merge' (WhileLoop cond') ) seq_blocker <- asksEngineEnv $ blockHoistSeq . envHoistBlockers (loopres, loopstms, hoisted) <- enterLoop . consumeMerge $ bindMerge (zipWith withRes merge' (bodyResult loopbody)) . wrapbody $ blockIf ( hasFree boundnames `orIf` isConsumed `orIf` seq_blocker `orIf` notWorthHoisting ) (bodyStms loopbody) $ do let params_usages = map (\p -> if unique (paramDeclType p) then UT.consumedU else mempty) params' (res, uses) <- simplifyResult params_usages $ bodyResult loopbody pure (res, uses <> isDoLoopResult res) loopbody' <- constructBody loopstms loopres pure (DoLoop merge' form' loopbody', hoisted) where fparamnames = namesFromList (map (paramName . fst) merge) consumeMerge = localVtable $ flip (foldl' (flip ST.consume)) $ namesToList consumed_by_merge consumed_by_merge = freeIn $ map snd $ filter (unique . paramDeclType . fst) merge withRes (p, x) y = (p, x, y) simplifyExp _ _ (Op op) = do (op', stms) <- simplifyOp op pure (Op op', stms) simplifyExp usage _ (WithAcc inputs lam) = do (inputs', inputs_stms) <- fmap unzip . forM inputs $ \(shape, arrs, op) -> do (op', op_stms) <- case op of Nothing -> pure (Nothing, mempty) Just (op_lam, nes) -> do (op_lam', op_lam_stms) <- blockMigrated (simplifyLambda mempty op_lam) nes' <- simplify nes pure (Just (op_lam', nes'), op_lam_stms) (,op_stms) <$> ((,,op') <$> simplify shape <*> simplify arrs) let noteAcc = ST.noteAccTokens (zip (map paramName (lambdaParams lam)) inputs') (lam', lam_stms) <- simplifyLambdaWith noteAcc (isFalse True) usage lam pure (WithAcc inputs' lam', mconcat inputs_stms <> lam_stms) simplifyExp _ _ e = do e' <- simplifyExpBase e pure (e', mempty) -- | Block hoisting of 'Index' statements introduced by migration. blockMigrated :: SimplifiableRep rep => SimpleM rep (Lambda (Wise rep), Stms (Wise rep)) -> SimpleM rep (Lambda (Wise rep), Stms (Wise rep)) blockMigrated = local withMigrationBlocker where withMigrationBlocker (ops, env) = let blockers = envHoistBlockers env par_blocker = blockHoistPar blockers blocker = par_blocker `orIf` isDeviceMigrated blockers' = blockers {blockHoistPar = blocker} env' = env {envHoistBlockers = blockers'} in (ops, env') -- | Statement is a scalar read from a single element array of rank one. isDeviceMigrated :: SimplifiableRep rep => BlockPred (Wise rep) isDeviceMigrated vtable _ stm | BasicOp (Index arr slice) <- stmExp stm, [DimFix idx] <- unSlice slice, idx == intConst Int64 0, Just arr_t <- ST.lookupType arr vtable, [size] <- arrayDims arr_t, size == intConst Int64 1 = True | otherwise = False -- The simple nonrecursive case that we can perform without bottom-up -- information. simplifyExpBase :: SimplifiableRep rep => Exp (Wise rep) -> SimpleM rep (Exp (Wise rep)) Special case for simplification of commutative where we -- arrange the operands in sorted order. This can make expressions more identical , which helps CSE . simplifyExpBase (BasicOp (BinOp op x y)) | commutativeBinOp op = do x' <- simplify x y' <- simplify y pure $ BasicOp $ BinOp op (min x' y') (max x' y') simplifyExpBase e = mapExpM hoist e where hoist = identityMapper { mapOnSubExp = simplify, mapOnVName = simplify, mapOnRetType = simplify, mapOnBranchType = simplify } type SimplifiableRep rep = ( ASTRep rep, Simplifiable (LetDec rep), Simplifiable (FParamInfo rep), Simplifiable (LParamInfo rep), Simplifiable (RetType rep), Simplifiable (BranchType rep), TraverseOpStms (Wise rep), CanBeWise (OpC rep), ST.IndexOp (Op (Wise rep)), AliasedOp (Op (Wise rep)), RephraseOp (OpC rep), BuilderOps (Wise rep), IsOp (Op rep) ) class Simplifiable e where simplify :: SimplifiableRep rep => e -> SimpleM rep e instance (Simplifiable a, Simplifiable b) => Simplifiable (a, b) where simplify (x, y) = (,) <$> simplify x <*> simplify y instance (Simplifiable a, Simplifiable b, Simplifiable c) => Simplifiable (a, b, c) where simplify (x, y, z) = (,,) <$> simplify x <*> simplify y <*> simplify z -- Convenient for Scatter. instance Simplifiable Int where simplify = pure instance Simplifiable a => Simplifiable (Maybe a) where simplify Nothing = pure Nothing simplify (Just x) = Just <$> simplify x instance Simplifiable a => Simplifiable [a] where simplify = mapM simplify instance Simplifiable SubExp where simplify (Var name) = do stm <- ST.lookupSubExp name <$> askVtable case stm of Just (Constant v, cs) -> do changed usedCerts cs pure $ Constant v Just (Var id', cs) -> do changed usedCerts cs pure $ Var id' _ -> pure $ Var name simplify (Constant v) = pure $ Constant v instance Simplifiable SubExpRes where simplify (SubExpRes cs se) = do cs' <- simplify cs (se', se_cs) <- collectCerts $ simplify se pure $ SubExpRes (se_cs <> cs') se' instance Simplifiable () where simplify = pure instance Simplifiable VName where simplify v = do se <- ST.lookupSubExp v <$> askVtable case se of Just (Var v', cs) -> do changed usedCerts cs pure v' _ -> pure v instance Simplifiable d => Simplifiable (ShapeBase d) where simplify = fmap Shape . simplify . shapeDims instance Simplifiable ExtSize where simplify (Free se) = Free <$> simplify se simplify (Ext x) = pure $ Ext x instance Simplifiable Space where simplify (ScalarSpace ds t) = ScalarSpace <$> simplify ds <*> pure t simplify s = pure s instance Simplifiable PrimType where simplify = pure instance Simplifiable shape => Simplifiable (TypeBase shape u) where simplify (Array et shape u) = Array <$> simplify et <*> simplify shape <*> pure u simplify (Acc acc ispace ts u) = Acc <$> simplify acc <*> simplify ispace <*> simplify ts <*> pure u simplify (Mem space) = Mem <$> simplify space simplify (Prim bt) = pure $ Prim bt instance Simplifiable d => Simplifiable (DimIndex d) where simplify (DimFix i) = DimFix <$> simplify i simplify (DimSlice i n s) = DimSlice <$> simplify i <*> simplify n <*> simplify s instance Simplifiable d => Simplifiable (Slice d) where simplify = traverse simplify simplifyLambda :: SimplifiableRep rep => Names -> Lambda (Wise rep) -> SimpleM rep (Lambda (Wise rep), Stms (Wise rep)) simplifyLambda extra_bound lam = do par_blocker <- asksEngineEnv $ blockHoistPar . envHoistBlockers simplifyLambdaMaybeHoist (par_blocker `orIf` hasFree extra_bound) mempty lam simplifyLambdaNoHoisting :: SimplifiableRep rep => Lambda (Wise rep) -> SimpleM rep (Lambda (Wise rep)) simplifyLambdaNoHoisting lam = fst <$> simplifyLambdaMaybeHoist (isFalse False) mempty lam simplifyLambdaMaybeHoist :: SimplifiableRep rep => BlockPred (Wise rep) -> UT.UsageTable -> Lambda (Wise rep) -> SimpleM rep (Lambda (Wise rep), Stms (Wise rep)) simplifyLambdaMaybeHoist = simplifyLambdaWith id simplifyLambdaWith :: SimplifiableRep rep => (ST.SymbolTable (Wise rep) -> ST.SymbolTable (Wise rep)) -> BlockPred (Wise rep) -> UT.UsageTable -> Lambda (Wise rep) -> SimpleM rep (Lambda (Wise rep), Stms (Wise rep)) simplifyLambdaWith f blocked usage lam@(Lambda params body rettype) = do params' <- mapM (traverse simplify) params let paramnames = namesFromList $ boundByLambda lam (hoisted, body') <- bindLParams params' . localVtable f $ simplifyBody (blocked `orIf` hasFree paramnames `orIf` isConsumed) usage (map (const mempty) rettype) body rettype' <- simplify rettype pure (Lambda params' body' rettype', hoisted) instance Simplifiable Certs where simplify (Certs ocs) = Certs . nubOrd . concat <$> mapM check ocs where check idd = do vv <- ST.lookupSubExp idd <$> askVtable case vv of Just (Constant _, Certs cs) -> pure cs Just (Var idd', _) -> pure [idd'] _ -> pure [idd] simplifyFun :: SimplifiableRep rep => FunDef (Wise rep) -> SimpleM rep (FunDef (Wise rep)) simplifyFun (FunDef entry attrs fname rettype params body) = do rettype' <- simplify rettype params' <- mapM (traverse simplify) params let usages = map (usageFromDiet . diet . declExtTypeOf) rettype' body' <- bindFParams params $ simplifyBodyNoHoisting mempty usages body pure $ FunDef entry attrs fname rettype' params' body'
null
https://raw.githubusercontent.com/diku-dk/futhark/174e8d862def6f52d5c9a36fa3aa6e746049776e/src/Futhark/Optimise/Simplify/Engine.hs
haskell
# LANGUAGE Strict # | Perform general rule-based simplification based on data dependency information. This module will: * Hoist expressions out of loops (including lambdas) and branches. This is done as aggressively as possible. * Apply simplification rules (see If you just want to run the simplifier as simply as possible, you * Building blocks | Blocker for hoisting out of parallel loops. | Blocker for hoisting out of sequential loops. | Blocker for hoisting out of branches. | A function that protects a hoisted operation (if possible). The (or equivalently, a boolean indicating whether a loop has nonzero trip count). that is true when the value of the statement will actually be used. to re-run the simplifier. | Indicate in the symbol table that we have descended into a loop. | We are willing to hoist potentially unsafe statements out of loops, but they must be protected by adding a branch on top of them. infinite loop Produces a true subexpression if the pattern (as in a 'Case') matches the subexpression. | We are willing to hoist potentially unsafe statements out of matches, but they must be protected by adding a branch on top of them. (This means such hoisting is not worth it unless they are in turn hoisted out of a loop somewhere.) | Scrutinee. | Pattern of this case. | Statements that are not worth hoisting out of loops, because they are unsafe, and added safety (by 'protectLoopHoisted') may inhibit further optimisation. Top-down simplify a statement (including copy propagation into the pattern and such). Does not recurse into any sub-Bodies or Ops. Does not copy-propagate into the pattern and similar, as it is assumed 'nonrecSimplifyStm' has already touched it (and worst case, it'll get it on the next round of the overall fixpoint iteration.) We need to do a final pass to ensure that nothing is hoisted past something that it depends on. Nothing to optimise - see if hoistable. No, not hoistable. Dead statement. Used to be False, but let's try it out. We are unwilling to hoist things that are unsafe or costly, except if they are invariant to the most enclosing loop, because in that case they will also be hoisted past that loop. We also try very hard to hoist allocations or anything that contributes to memory or array size, because that will allow allocations to be hoisted. Avoid hoisting out something that might change the asymptotics of the program. possible. Hoist things that are free. Hoist aggressively out of versioning branches. | Simplify a single body. | Simplify a single body. | Simplify a single 'Result'. | Block hoisting of 'Index' statements introduced by migration. | Statement is a scalar read from a single element array of rank one. The simple nonrecursive case that we can perform without bottom-up information. arrange the operands in sorted order. This can make expressions Convenient for Scatter.
# LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # * Perform common - subexpression elimination ( CSE ) . " Futhark . Optimise . Simplification . Rules " ) . may prefer to use the " Futhark . Optimise . Simplify " module . module Futhark.Optimise.Simplify.Engine * Monadic interface SimpleM, runSimpleM, SimpleOps (..), SimplifyOp, bindableSimpleOps, Env (envHoistBlockers, envRules), emptyEnv, HoistBlockers (..), neverBlocks, noExtraHoistBlockers, neverHoist, BlockPred, orIf, hasFree, isConsumed, isConsuming, isFalse, isOp, isNotSafe, isDeviceMigrated, asksEngineEnv, askVtable, localVtable, SimplifiableRep, Simplifiable (..), simplifyFun, simplifyStms, simplifyStmsWithUsage, simplifyLambda, simplifyLambdaNoHoisting, bindLParams, simplifyBody, ST.SymbolTable, hoistStms, blockIf, blockMigrated, enterLoop, constructBody, module Futhark.Optimise.Simplify.Rep, ) where import Control.Monad.Reader import Control.Monad.State.Strict import Data.Either import Data.List (find, foldl', inits, mapAccumL) import Data.Map qualified as M import Data.Maybe import Futhark.Analysis.SymbolTable qualified as ST import Futhark.Analysis.UsageTable qualified as UT import Futhark.Construct import Futhark.IR import Futhark.IR.Prop.Aliases import Futhark.Optimise.Simplify.Rep import Futhark.Optimise.Simplify.Rule import Futhark.Util (nubOrd) data HoistBlockers rep = HoistBlockers blockHoistPar :: BlockPred (Wise rep), blockHoistSeq :: BlockPred (Wise rep), blockHoistBranch :: BlockPred (Wise rep), isAllocation :: Stm (Wise rep) -> Bool } noExtraHoistBlockers :: HoistBlockers rep noExtraHoistBlockers = HoistBlockers neverBlocks neverBlocks neverBlocks (const False) neverHoist :: HoistBlockers rep neverHoist = HoistBlockers alwaysBlocks alwaysBlocks alwaysBlocks (const False) data Env rep = Env { envRules :: RuleBook (Wise rep), envHoistBlockers :: HoistBlockers rep, envVtable :: ST.SymbolTable (Wise rep) } emptyEnv :: RuleBook (Wise rep) -> HoistBlockers rep -> Env rep emptyEnv rules blockers = Env { envRules = rules, envHoistBlockers = blockers, envVtable = mempty } first operand is the condition of the ' Case ' we have hoisted out of type Protect m = SubExp -> Pat (LetDec (Rep m)) -> Op (Rep m) -> Maybe (m ()) type SimplifyOp rep op = op -> SimpleM rep (op, Stms (Wise rep)) data SimpleOps rep = SimpleOps { mkExpDecS :: ST.SymbolTable (Wise rep) -> Pat (LetDec (Wise rep)) -> Exp (Wise rep) -> SimpleM rep (ExpDec (Wise rep)), mkBodyS :: ST.SymbolTable (Wise rep) -> Stms (Wise rep) -> Result -> SimpleM rep (Body (Wise rep)), | Make a hoisted Op safe . The SubExp is a boolean protectHoistedOpS :: Protect (Builder (Wise rep)), opUsageS :: Op (Wise rep) -> UT.UsageTable, simplifyPatFromExpS :: Pat (LetDec rep) -> Exp (Wise rep) -> SimpleM rep (Pat (LetDec rep)), simplifyOpS :: SimplifyOp rep (Op (Wise rep)) } bindableSimpleOps :: (SimplifiableRep rep, Buildable rep) => SimplifyOp rep (Op (Wise rep)) -> SimpleOps rep bindableSimpleOps = SimpleOps mkExpDecS' mkBodyS' protectHoistedOpS' (const mempty) simplifyPatFromExp where mkExpDecS' _ pat e = pure $ mkExpDec pat e mkBodyS' _ stms res = pure $ mkBody stms res protectHoistedOpS' _ _ _ = Nothing simplifyPatFromExp pat _ = traverse simplify pat newtype SimpleM rep a = SimpleM ( ReaderT (SimpleOps rep, Env rep) (State (VNameSource, Bool, Certs)) a ) deriving ( Applicative, Functor, Monad, MonadReader (SimpleOps rep, Env rep), MonadState (VNameSource, Bool, Certs) ) instance MonadFreshNames (SimpleM rep) where putNameSource src = modify $ \(_, b, c) -> (src, b, c) getNameSource = gets $ \(a, _, _) -> a instance SimplifiableRep rep => HasScope (Wise rep) (SimpleM rep) where askScope = ST.toScope <$> askVtable lookupType name = do vtable <- askVtable case ST.lookupType name vtable of Just t -> pure t Nothing -> error $ "SimpleM.lookupType: cannot find variable " ++ prettyString name ++ " in symbol table." instance SimplifiableRep rep => LocalScope (Wise rep) (SimpleM rep) where localScope types = localVtable (<> ST.fromScope types) runSimpleM :: SimpleM rep a -> SimpleOps rep -> Env rep -> VNameSource -> ((a, Bool), VNameSource) runSimpleM (SimpleM m) simpl env src = let (x, (src', b, _)) = runState (runReaderT m (simpl, env)) (src, False, mempty) in ((x, b), src') askEngineEnv :: SimpleM rep (Env rep) askEngineEnv = asks snd asksEngineEnv :: (Env rep -> a) -> SimpleM rep a asksEngineEnv f = f <$> askEngineEnv askVtable :: SimpleM rep (ST.SymbolTable (Wise rep)) askVtable = asksEngineEnv envVtable localVtable :: (ST.SymbolTable (Wise rep) -> ST.SymbolTable (Wise rep)) -> SimpleM rep a -> SimpleM rep a localVtable f = local $ \(ops, env) -> (ops, env {envVtable = f $ envVtable env}) collectCerts :: SimpleM rep a -> SimpleM rep (a, Certs) collectCerts m = do x <- m (a, b, cs) <- get put (a, b, mempty) pure (x, cs) | that we have changed something and it would be a good idea changed :: SimpleM rep () changed = modify $ \(src, _, cs) -> (src, True, cs) usedCerts :: Certs -> SimpleM rep () usedCerts cs = modify $ \(a, b, c) -> (a, b, cs <> c) enterLoop :: SimpleM rep a -> SimpleM rep a enterLoop = localVtable ST.deepen bindFParams :: SimplifiableRep rep => [FParam (Wise rep)] -> SimpleM rep a -> SimpleM rep a bindFParams params = localVtable $ ST.insertFParams params bindLParams :: SimplifiableRep rep => [LParam (Wise rep)] -> SimpleM rep a -> SimpleM rep a bindLParams params = localVtable $ \vtable -> foldr ST.insertLParam vtable params bindArrayLParams :: SimplifiableRep rep => [LParam (Wise rep)] -> SimpleM rep a -> SimpleM rep a bindArrayLParams params = localVtable $ \vtable -> foldl' (flip ST.insertLParam) vtable params bindMerge :: SimplifiableRep rep => [(FParam (Wise rep), SubExp, SubExpRes)] -> SimpleM rep a -> SimpleM rep a bindMerge = localVtable . ST.insertLoopMerge bindLoopVar :: SimplifiableRep rep => VName -> IntType -> SubExp -> SimpleM rep a -> SimpleM rep a bindLoopVar var it bound = localVtable $ ST.insertLoopVar var it bound makeSafe :: Exp rep -> Maybe (Exp rep) makeSafe (BasicOp (BinOp (SDiv t _) x y)) = Just $ BasicOp (BinOp (SDiv t Safe) x y) makeSafe (BasicOp (BinOp (SDivUp t _) x y)) = Just $ BasicOp (BinOp (SDivUp t Safe) x y) makeSafe (BasicOp (BinOp (SQuot t _) x y)) = Just $ BasicOp (BinOp (SQuot t Safe) x y) makeSafe (BasicOp (BinOp (UDiv t _) x y)) = Just $ BasicOp (BinOp (UDiv t Safe) x y) makeSafe (BasicOp (BinOp (UDivUp t _) x y)) = Just $ BasicOp (BinOp (UDivUp t Safe) x y) makeSafe (BasicOp (BinOp (SMod t _) x y)) = Just $ BasicOp (BinOp (SMod t Safe) x y) makeSafe (BasicOp (BinOp (SRem t _) x y)) = Just $ BasicOp (BinOp (SRem t Safe) x y) makeSafe (BasicOp (BinOp (UMod t _) x y)) = Just $ BasicOp (BinOp (UMod t Safe) x y) makeSafe _ = Nothing emptyOfType :: MonadBuilder m => [VName] -> Type -> m (Exp (Rep m)) emptyOfType _ Mem {} = error "emptyOfType: Cannot hoist non-existential memory." emptyOfType _ Acc {} = error "emptyOfType: Cannot hoist accumulator." emptyOfType _ (Prim pt) = pure $ BasicOp $ SubExp $ Constant $ blankPrimValue pt emptyOfType ctx_names (Array et shape _) = do let dims = map zeroIfContext $ shapeDims shape pure $ BasicOp $ Scratch et dims where zeroIfContext (Var v) | v `elem` ctx_names = intConst Int64 0 zeroIfContext se = se protectIf :: MonadBuilder m => Protect m -> (Exp (Rep m) -> Bool) -> SubExp -> Stm (Rep m) -> m () protectIf _ _ taken (Let pat aux (Match [cond] [Case [Just (BoolValue True)] taken_body] untaken_body (MatchDec if_ts MatchFallback))) = do cond' <- letSubExp "protect_cond_conj" $ BasicOp $ BinOp LogAnd taken cond auxing aux . letBind pat $ Match [cond'] [Case [Just (BoolValue True)] taken_body] untaken_body $ MatchDec if_ts MatchFallback protectIf _ _ taken (Let pat aux (BasicOp (Assert cond msg loc))) = do not_taken <- letSubExp "loop_not_taken" $ BasicOp $ UnOp Not taken cond' <- letSubExp "protect_assert_disj" $ BasicOp $ BinOp LogOr not_taken cond auxing aux $ letBind pat $ BasicOp $ Assert cond' msg loc protectIf protect _ taken (Let pat aux (Op op)) | Just m <- protect taken pat op = auxing aux m protectIf _ f taken (Let pat aux e) | f e = case makeSafe e of Just e' -> auxing aux $ letBind pat e' Nothing -> do taken_body <- eBody [pure e] untaken_body <- eBody $ map (emptyOfType $ patNames pat) (patTypes pat) if_ts <- expTypesFromPat pat auxing aux . letBind pat $ Match [taken] [Case [Just $ BoolValue True] taken_body] untaken_body $ MatchDec if_ts MatchFallback protectIf _ _ _ stm = addStm stm protectLoopHoisted :: SimplifiableRep rep => [(FParam (Wise rep), SubExp)] -> LoopForm (Wise rep) -> SimpleM rep (a, b, Stms (Wise rep)) -> SimpleM rep (a, b, Stms (Wise rep)) protectLoopHoisted merge form m = do (x, y, stms) <- m ops <- asks $ protectHoistedOpS . fst stms' <- runBuilder_ $ do if not $ all (safeExp . stmExp) stms then do is_nonempty <- checkIfNonEmpty mapM_ (protectIf ops (not . safeExp) is_nonempty) stms else addStms stms pure (x, y, stms') where checkIfNonEmpty = case form of WhileLoop cond | Just (_, cond_init) <- find ((== cond) . paramName . fst) merge -> pure cond_init ForLoop _ it bound _ -> letSubExp "loop_nonempty" $ BasicOp $ CmpOp (CmpSlt it) (intConst it 0) bound matching :: BuilderOps rep => [(SubExp, Maybe PrimValue)] -> Builder rep SubExp matching = letSubExp "match" <=< eAll <=< sequence . mapMaybe cmp where cmp (se, Just (BoolValue True)) = Just $ pure se cmp (se, Just v) = Just . letSubExp "match_val" . BasicOp $ CmpOp (CmpEq (primValueType v)) se (Constant v) cmp (_, Nothing) = Nothing matchingExactlyThis :: BuilderOps rep => [SubExp] -> [[Maybe PrimValue]] -> [Maybe PrimValue] -> Builder rep SubExp matchingExactlyThis ses prior this = do prior_matches <- mapM (matching . zip ses) prior letSubExp "matching_just_this" =<< eBinOp LogAnd (eUnOp Not (eAny prior_matches)) (eSubExp =<< matching (zip ses this)) protectCaseHoisted :: SimplifiableRep rep => [SubExp] -> | Pattern of previosu cases . [[Maybe PrimValue]] -> [Maybe PrimValue] -> SimpleM rep (Stms (Wise rep), a) -> SimpleM rep (Stms (Wise rep), a) protectCaseHoisted ses prior vs m = do (hoisted, x) <- m ops <- asks $ protectHoistedOpS . fst hoisted' <- runBuilder_ $ do if not $ all (safeExp . stmExp) hoisted then do cond' <- matchingExactlyThis ses prior vs mapM_ (protectIf ops unsafeOrCostly cond') hoisted else addStms hoisted pure (hoisted', x) where unsafeOrCostly e = not (safeExp e) || not (cheapExp e) notWorthHoisting :: ASTRep rep => BlockPred rep notWorthHoisting _ _ (Let pat _ e) = not (safeExp e) && any ((> 0) . arrayRank) (patTypes pat) nonrecSimplifyStm :: SimplifiableRep rep => Stm (Wise rep) -> SimpleM rep (Stm (Wise rep)) nonrecSimplifyStm (Let pat (StmAux cs attrs (_, dec)) e) = do cs' <- simplify cs e' <- simplifyExpBase e simplifyPat <- asks $ simplifyPatFromExpS . fst (pat', pat_cs) <- collectCerts $ simplifyPat (removePatWisdom pat) e' let aux' = StmAux (cs' <> pat_cs) attrs dec pure $ mkWiseStm pat' aux' e' Bottom - up simplify a statement . Recurses into sub - Bodies and Ops . recSimplifyStm :: SimplifiableRep rep => Stm (Wise rep) -> UT.UsageTable -> SimpleM rep (Stms (Wise rep), Stm (Wise rep)) recSimplifyStm (Let pat (StmAux cs attrs (_, dec)) e) usage = do ((e', e_hoisted), e_cs) <- collectCerts $ simplifyExp (usage <> UT.usageInPat pat) pat e let aux' = StmAux (cs <> e_cs) attrs dec pure (e_hoisted, mkWiseStm (removePatWisdom pat) aux' e') hoistStms :: SimplifiableRep rep => RuleBook (Wise rep) -> BlockPred (Wise rep) -> Stms (Wise rep) -> SimpleM rep (a, UT.UsageTable) -> SimpleM rep (a, Stms (Wise rep), Stms (Wise rep)) hoistStms rules block orig_stms final = do (a, blocked, hoisted) <- simplifyStmsBottomUp orig_stms unless (null hoisted) changed pure (a, stmsFromList blocked, stmsFromList hoisted) where simplifyStmsBottomUp stms = do opUsage <- asks $ opUsageS . fst let usageInStm stm = UT.usageInStm stm <> case stmExp stm of Op op -> opUsage op _ -> mempty (x, _, stms') <- hoistableStms usageInStm stms let (blocked, hoisted) = partitionEithers $ blockUnhoistedDeps stms' pure (x, blocked, hoisted) descend usageInStm stms m = case stmsHead stms of Nothing -> m Just (stms_h, stms_t) -> localVtable (ST.insertStm stms_h) $ do (x, usage, stms_t') <- descend usageInStm stms_t m process usageInStm stms_h stms_t' usage x process usageInStm stm stms usage x = do vtable <- askVtable res <- bottomUpSimplifyStm rules (vtable, usage) stm case res of | block vtable usage stm -> pure ( x, expandUsage usageInStm vtable usage stm `UT.without` provides stm, Left stm : stms ) | otherwise -> Yes , . pure ( x, expandUsage usageInStm vtable usage stm, Right stm : stms ) Just optimstms -> do changed descend usageInStm optimstms $ pure (x, usage, stms) hoistableStms usageInStm stms = case stmsHead stms of Nothing -> do (x, usage) <- final pure (x, usage, mempty) Just (stms_h, stms_t) -> do stms_h' <- nonrecSimplifyStm stms_h vtable <- askVtable simplified <- topDownSimplifyStm rules vtable stms_h' case simplified of Just newstms -> do changed hoistableStms usageInStm (newstms <> stms_t) Nothing -> do (x, usage, stms_t') <- localVtable (ST.insertStm stms_h') $ hoistableStms usageInStm stms_t if not $ any (`UT.isUsedDirectly` usage) $ provides stms_h' pure (x, usage, stms_t') else do (stms_h_stms, stms_h'') <- recSimplifyStm stms_h' usage descend usageInStm stms_h_stms $ process usageInStm stms_h'' stms_t' usage x blockUnhoistedDeps :: ASTRep rep => [Either (Stm rep) (Stm rep)] -> [Either (Stm rep) (Stm rep)] blockUnhoistedDeps = snd . mapAccumL block mempty where block blocked (Left need) = (blocked <> namesFromList (provides need), Left need) block blocked (Right need) | blocked `namesIntersect` freeIn need = (blocked <> namesFromList (provides need), Left need) | otherwise = (blocked, Right need) provides :: Stm rep -> [VName] provides = patNames . stmPat expandUsage :: Aliased rep => (Stm rep -> UT.UsageTable) -> ST.SymbolTable rep -> UT.UsageTable -> Stm rep -> UT.UsageTable expandUsage usageInStm vtable utable stm@(Let pat aux e) = stmUsages <> utable where stmUsages = UT.expand (`ST.lookupAliases` vtable) (usageInStm stm <> usageThroughAliases) <> ( if any (`UT.isSize` utable) (patNames pat) then UT.sizeUsages (freeIn (stmAuxCerts aux) <> freeIn e) else mempty ) usageThroughAliases = mconcat . mapMaybe usageThroughBindeeAliases $ zip (patNames pat) (patAliases pat) usageThroughBindeeAliases (name, aliases) = do uses <- UT.lookup name utable pure . mconcat $ map (`UT.usage` (uses `UT.withoutU` UT.presentU)) $ namesToList aliases type BlockPred rep = ST.SymbolTable rep -> UT.UsageTable -> Stm rep -> Bool neverBlocks :: BlockPred rep neverBlocks _ _ _ = False alwaysBlocks :: BlockPred rep alwaysBlocks _ _ _ = True isFalse :: Bool -> BlockPred rep isFalse b _ _ _ = not b orIf :: BlockPred rep -> BlockPred rep -> BlockPred rep orIf p1 p2 body vtable need = p1 body vtable need || p2 body vtable need andAlso :: BlockPred rep -> BlockPred rep -> BlockPred rep andAlso p1 p2 body vtable need = p1 body vtable need && p2 body vtable need isConsumed :: BlockPred rep isConsumed _ utable = any (`UT.isConsumed` utable) . patNames . stmPat isOp :: BlockPred rep isOp _ _ (Let _ _ Op {}) = True isOp _ _ _ = False constructBody :: SimplifiableRep rep => Stms (Wise rep) -> Result -> SimpleM rep (Body (Wise rep)) constructBody stms res = fmap fst . runBuilder . buildBody_ $ do addStms stms pure res blockIf :: SimplifiableRep rep => BlockPred (Wise rep) -> Stms (Wise rep) -> SimpleM rep (a, UT.UsageTable) -> SimpleM rep (a, Stms (Wise rep), Stms (Wise rep)) blockIf block stms m = do rules <- asksEngineEnv envRules hoistStms rules block stms m hasFree :: ASTRep rep => Names -> BlockPred rep hasFree ks _ _ need = ks `namesIntersect` freeIn need isNotSafe :: ASTRep rep => BlockPred rep isNotSafe _ _ = not . safeExp . stmExp isConsuming :: Aliased rep => BlockPred rep isConsuming _ _ = isUpdate . stmExp where isUpdate e = consumedInExp e /= mempty isNotCheap :: ASTRep rep => BlockPred rep isNotCheap _ _ = not . cheapStm cheapStm :: ASTRep rep => Stm rep -> Bool cheapStm = cheapExp . stmExp cheapExp :: ASTRep rep => Exp rep -> Bool cheapExp (BasicOp BinOp {}) = True cheapExp (BasicOp SubExp {}) = True cheapExp (BasicOp UnOp {}) = True cheapExp (BasicOp CmpOp {}) = True cheapExp (BasicOp ConvOp {}) = True cheapExp (BasicOp Assert {}) = True cheapExp (BasicOp Copy {}) = False cheapExp (BasicOp Replicate {}) = False cheapExp (BasicOp Concat {}) = False cheapExp (BasicOp Manifest {}) = False cheapExp DoLoop {} = False cheapExp (Match _ cases defbranch _) = all (all cheapStm . bodyStms . caseBody) cases && all cheapStm (bodyStms defbranch) cheapExp (Op op) = cheapOp op loopInvariantStm :: ASTRep rep => ST.SymbolTable rep -> Stm rep -> Bool loopInvariantStm vtable = all (`nameIn` ST.availableAtClosestLoop vtable) . namesToList . freeIn matchBlocker :: SimplifiableRep rep => [SubExp] -> MatchDec rt -> SimpleM rep (BlockPred (Wise rep)) matchBlocker cond (MatchDec _ ifsort) = do is_alloc_fun <- asksEngineEnv $ isAllocation . envHoistBlockers branch_blocker <- asksEngineEnv $ blockHoistBranch . envHoistBlockers vtable <- askVtable cond_loop_invariant = all (`nameIn` ST.availableAtClosestLoop vtable) $ namesToList $ freeIn cond desirableToHoist usage stm = is_alloc_fun stm || ( ST.loopDepth vtable > 0 && cond_loop_invariant && ifsort /= MatchFallback && loopInvariantStm vtable stm && all primType (patTypes (stmPat stm)) ) || ( ifsort /= MatchFallback && any (`UT.isSize` usage) (patNames (stmPat stm)) && all primType (patTypes (stmPat stm)) ) notDesirableToHoist _ usage stm = not $ desirableToHoist usage stm No matter what , we always want to hoist constants as much as isNotHoistableBnd _ _ (Let _ _ (BasicOp ArrayLit {})) = False isNotHoistableBnd _ _ (Let _ _ (BasicOp SubExp {})) = False isNotHoistableBnd _ _ (Let _ _ (BasicOp Reshape {})) = False isNotHoistableBnd _ _ (Let _ _ (BasicOp Rearrange {})) = False isNotHoistableBnd _ _ (Let _ _ (BasicOp Rotate {})) = False isNotHoistableBnd _ _ (Let _ _ (BasicOp (Index _ slice))) = null $ sliceDims slice isNotHoistableBnd _ _ stm | is_alloc_fun stm = False isNotHoistableBnd _ _ _ = ifsort /= MatchEquiv block = branch_blocker `orIf` ( (isNotSafe `orIf` isNotCheap `orIf` isNotHoistableBnd) `andAlso` notDesirableToHoist ) `orIf` isConsuming pure block simplifyBody :: SimplifiableRep rep => BlockPred (Wise rep) -> UT.UsageTable -> [UT.Usages] -> Body (Wise rep) -> SimpleM rep (Stms (Wise rep), Body (Wise rep)) simplifyBody blocker usage res_usages (Body _ stms res) = do (res', stms', hoisted) <- blockIf blocker stms $ do (res', res_usage) <- simplifyResult res_usages res pure (res', res_usage <> usage) body' <- constructBody stms' res' pure (hoisted, body') simplifyBodyNoHoisting :: SimplifiableRep rep => UT.UsageTable -> [UT.Usages] -> Body (Wise rep) -> SimpleM rep (Body (Wise rep)) simplifyBodyNoHoisting usage res_usages body = snd <$> simplifyBody (isFalse False) usage res_usages body usageFromDiet :: Diet -> UT.Usages usageFromDiet Consume = UT.consumedU usageFromDiet _ = mempty simplifyResult :: SimplifiableRep rep => [UT.Usages] -> Result -> SimpleM rep (Result, UT.UsageTable) simplifyResult usages res = do res' <- mapM simplify res vtable <- askVtable let more_usages = mconcat $ do (u, Var v) <- zip usages $ map resSubExp res let als_usages = map (`UT.usage` (u `UT.withoutU` UT.presentU)) (namesToList (ST.lookupAliases v vtable)) UT.usage v u : als_usages pure ( res', UT.usages (freeIn res') <> foldMap UT.inResultUsage (namesToList (freeIn res')) <> more_usages ) isDoLoopResult :: Result -> UT.UsageTable isDoLoopResult = mconcat . map checkForVar where checkForVar (SubExpRes _ (Var ident)) = UT.inResultUsage ident checkForVar _ = mempty simplifyStms :: SimplifiableRep rep => Stms (Wise rep) -> SimpleM rep (Stms (Wise rep)) simplifyStms stms = do simplifyStmsWithUsage all_used stms where all_used = UT.usages (namesFromList (M.keys (scopeOf stms))) simplifyStmsWithUsage :: SimplifiableRep rep => UT.UsageTable -> Stms (Wise rep) -> SimpleM rep (Stms (Wise rep)) simplifyStmsWithUsage usage stms = do ((), stms', _) <- blockIf (isFalse False) stms $ pure ((), usage) pure stms' simplifyOp :: Op (Wise rep) -> SimpleM rep (Op (Wise rep), Stms (Wise rep)) simplifyOp op = do f <- asks $ simplifyOpS . fst f op simplifyExp :: SimplifiableRep rep => UT.UsageTable -> Pat (LetDec (Wise rep)) -> Exp (Wise rep) -> SimpleM rep (Exp (Wise rep), Stms (Wise rep)) simplifyExp usage (Pat pes) (Match ses cases defbody ifdec@(MatchDec ts ifsort)) = do let pes_usages = map (fromMaybe mempty . (`UT.lookup` usage) . patElemName) pes ses' <- mapM simplify ses ts' <- mapM simplify ts let pats = map casePat cases block <- matchBlocker ses ifdec (cases_hoisted, cases') <- unzip <$> zipWithM (simplifyCase block ses' pes_usages) (inits pats) cases (defbody_hoisted, defbody') <- protectCaseHoisted ses' pats [] $ simplifyBody block usage pes_usages defbody pure ( Match ses' cases' defbody' $ MatchDec ts' ifsort, mconcat $ defbody_hoisted : cases_hoisted ) where simplifyCase block ses' pes_usages prior (Case vs body) = do (hoisted, body') <- protectCaseHoisted ses' prior vs $ simplifyBody block usage pes_usages body pure (hoisted, Case vs body') simplifyExp _ _ (DoLoop merge form loopbody) = do let (params, args) = unzip merge params' <- mapM (traverse simplify) params args' <- mapM simplify args let merge' = zip params' args' (form', boundnames, wrapbody) <- case form of ForLoop loopvar it boundexp loopvars -> do boundexp' <- simplify boundexp let (loop_params, loop_arrs) = unzip loopvars loop_params' <- mapM (traverse simplify) loop_params loop_arrs' <- mapM simplify loop_arrs let form' = ForLoop loopvar it boundexp' (zip loop_params' loop_arrs') pure ( form', namesFromList (loopvar : map paramName loop_params') <> fparamnames, bindLoopVar loopvar it boundexp' . protectLoopHoisted merge' form' . bindArrayLParams loop_params' ) WhileLoop cond -> do cond' <- simplify cond pure ( WhileLoop cond', fparamnames, protectLoopHoisted merge' (WhileLoop cond') ) seq_blocker <- asksEngineEnv $ blockHoistSeq . envHoistBlockers (loopres, loopstms, hoisted) <- enterLoop . consumeMerge $ bindMerge (zipWith withRes merge' (bodyResult loopbody)) . wrapbody $ blockIf ( hasFree boundnames `orIf` isConsumed `orIf` seq_blocker `orIf` notWorthHoisting ) (bodyStms loopbody) $ do let params_usages = map (\p -> if unique (paramDeclType p) then UT.consumedU else mempty) params' (res, uses) <- simplifyResult params_usages $ bodyResult loopbody pure (res, uses <> isDoLoopResult res) loopbody' <- constructBody loopstms loopres pure (DoLoop merge' form' loopbody', hoisted) where fparamnames = namesFromList (map (paramName . fst) merge) consumeMerge = localVtable $ flip (foldl' (flip ST.consume)) $ namesToList consumed_by_merge consumed_by_merge = freeIn $ map snd $ filter (unique . paramDeclType . fst) merge withRes (p, x) y = (p, x, y) simplifyExp _ _ (Op op) = do (op', stms) <- simplifyOp op pure (Op op', stms) simplifyExp usage _ (WithAcc inputs lam) = do (inputs', inputs_stms) <- fmap unzip . forM inputs $ \(shape, arrs, op) -> do (op', op_stms) <- case op of Nothing -> pure (Nothing, mempty) Just (op_lam, nes) -> do (op_lam', op_lam_stms) <- blockMigrated (simplifyLambda mempty op_lam) nes' <- simplify nes pure (Just (op_lam', nes'), op_lam_stms) (,op_stms) <$> ((,,op') <$> simplify shape <*> simplify arrs) let noteAcc = ST.noteAccTokens (zip (map paramName (lambdaParams lam)) inputs') (lam', lam_stms) <- simplifyLambdaWith noteAcc (isFalse True) usage lam pure (WithAcc inputs' lam', mconcat inputs_stms <> lam_stms) simplifyExp _ _ e = do e' <- simplifyExpBase e pure (e', mempty) blockMigrated :: SimplifiableRep rep => SimpleM rep (Lambda (Wise rep), Stms (Wise rep)) -> SimpleM rep (Lambda (Wise rep), Stms (Wise rep)) blockMigrated = local withMigrationBlocker where withMigrationBlocker (ops, env) = let blockers = envHoistBlockers env par_blocker = blockHoistPar blockers blocker = par_blocker `orIf` isDeviceMigrated blockers' = blockers {blockHoistPar = blocker} env' = env {envHoistBlockers = blockers'} in (ops, env') isDeviceMigrated :: SimplifiableRep rep => BlockPred (Wise rep) isDeviceMigrated vtable _ stm | BasicOp (Index arr slice) <- stmExp stm, [DimFix idx] <- unSlice slice, idx == intConst Int64 0, Just arr_t <- ST.lookupType arr vtable, [size] <- arrayDims arr_t, size == intConst Int64 1 = True | otherwise = False simplifyExpBase :: SimplifiableRep rep => Exp (Wise rep) -> SimpleM rep (Exp (Wise rep)) Special case for simplification of commutative where we more identical , which helps CSE . simplifyExpBase (BasicOp (BinOp op x y)) | commutativeBinOp op = do x' <- simplify x y' <- simplify y pure $ BasicOp $ BinOp op (min x' y') (max x' y') simplifyExpBase e = mapExpM hoist e where hoist = identityMapper { mapOnSubExp = simplify, mapOnVName = simplify, mapOnRetType = simplify, mapOnBranchType = simplify } type SimplifiableRep rep = ( ASTRep rep, Simplifiable (LetDec rep), Simplifiable (FParamInfo rep), Simplifiable (LParamInfo rep), Simplifiable (RetType rep), Simplifiable (BranchType rep), TraverseOpStms (Wise rep), CanBeWise (OpC rep), ST.IndexOp (Op (Wise rep)), AliasedOp (Op (Wise rep)), RephraseOp (OpC rep), BuilderOps (Wise rep), IsOp (Op rep) ) class Simplifiable e where simplify :: SimplifiableRep rep => e -> SimpleM rep e instance (Simplifiable a, Simplifiable b) => Simplifiable (a, b) where simplify (x, y) = (,) <$> simplify x <*> simplify y instance (Simplifiable a, Simplifiable b, Simplifiable c) => Simplifiable (a, b, c) where simplify (x, y, z) = (,,) <$> simplify x <*> simplify y <*> simplify z instance Simplifiable Int where simplify = pure instance Simplifiable a => Simplifiable (Maybe a) where simplify Nothing = pure Nothing simplify (Just x) = Just <$> simplify x instance Simplifiable a => Simplifiable [a] where simplify = mapM simplify instance Simplifiable SubExp where simplify (Var name) = do stm <- ST.lookupSubExp name <$> askVtable case stm of Just (Constant v, cs) -> do changed usedCerts cs pure $ Constant v Just (Var id', cs) -> do changed usedCerts cs pure $ Var id' _ -> pure $ Var name simplify (Constant v) = pure $ Constant v instance Simplifiable SubExpRes where simplify (SubExpRes cs se) = do cs' <- simplify cs (se', se_cs) <- collectCerts $ simplify se pure $ SubExpRes (se_cs <> cs') se' instance Simplifiable () where simplify = pure instance Simplifiable VName where simplify v = do se <- ST.lookupSubExp v <$> askVtable case se of Just (Var v', cs) -> do changed usedCerts cs pure v' _ -> pure v instance Simplifiable d => Simplifiable (ShapeBase d) where simplify = fmap Shape . simplify . shapeDims instance Simplifiable ExtSize where simplify (Free se) = Free <$> simplify se simplify (Ext x) = pure $ Ext x instance Simplifiable Space where simplify (ScalarSpace ds t) = ScalarSpace <$> simplify ds <*> pure t simplify s = pure s instance Simplifiable PrimType where simplify = pure instance Simplifiable shape => Simplifiable (TypeBase shape u) where simplify (Array et shape u) = Array <$> simplify et <*> simplify shape <*> pure u simplify (Acc acc ispace ts u) = Acc <$> simplify acc <*> simplify ispace <*> simplify ts <*> pure u simplify (Mem space) = Mem <$> simplify space simplify (Prim bt) = pure $ Prim bt instance Simplifiable d => Simplifiable (DimIndex d) where simplify (DimFix i) = DimFix <$> simplify i simplify (DimSlice i n s) = DimSlice <$> simplify i <*> simplify n <*> simplify s instance Simplifiable d => Simplifiable (Slice d) where simplify = traverse simplify simplifyLambda :: SimplifiableRep rep => Names -> Lambda (Wise rep) -> SimpleM rep (Lambda (Wise rep), Stms (Wise rep)) simplifyLambda extra_bound lam = do par_blocker <- asksEngineEnv $ blockHoistPar . envHoistBlockers simplifyLambdaMaybeHoist (par_blocker `orIf` hasFree extra_bound) mempty lam simplifyLambdaNoHoisting :: SimplifiableRep rep => Lambda (Wise rep) -> SimpleM rep (Lambda (Wise rep)) simplifyLambdaNoHoisting lam = fst <$> simplifyLambdaMaybeHoist (isFalse False) mempty lam simplifyLambdaMaybeHoist :: SimplifiableRep rep => BlockPred (Wise rep) -> UT.UsageTable -> Lambda (Wise rep) -> SimpleM rep (Lambda (Wise rep), Stms (Wise rep)) simplifyLambdaMaybeHoist = simplifyLambdaWith id simplifyLambdaWith :: SimplifiableRep rep => (ST.SymbolTable (Wise rep) -> ST.SymbolTable (Wise rep)) -> BlockPred (Wise rep) -> UT.UsageTable -> Lambda (Wise rep) -> SimpleM rep (Lambda (Wise rep), Stms (Wise rep)) simplifyLambdaWith f blocked usage lam@(Lambda params body rettype) = do params' <- mapM (traverse simplify) params let paramnames = namesFromList $ boundByLambda lam (hoisted, body') <- bindLParams params' . localVtable f $ simplifyBody (blocked `orIf` hasFree paramnames `orIf` isConsumed) usage (map (const mempty) rettype) body rettype' <- simplify rettype pure (Lambda params' body' rettype', hoisted) instance Simplifiable Certs where simplify (Certs ocs) = Certs . nubOrd . concat <$> mapM check ocs where check idd = do vv <- ST.lookupSubExp idd <$> askVtable case vv of Just (Constant _, Certs cs) -> pure cs Just (Var idd', _) -> pure [idd'] _ -> pure [idd] simplifyFun :: SimplifiableRep rep => FunDef (Wise rep) -> SimpleM rep (FunDef (Wise rep)) simplifyFun (FunDef entry attrs fname rettype params body) = do rettype' <- simplify rettype params' <- mapM (traverse simplify) params let usages = map (usageFromDiet . diet . declExtTypeOf) rettype' body' <- bindFParams params $ simplifyBodyNoHoisting mempty usages body pure $ FunDef entry attrs fname rettype' params' body'
9cf71a1aac571d177de4122e1168ff54ee781a514a0b5a86ee5c7883a57c5ef8
OtpChatBot/Ybot
talker_app_sup.erl
%%%----------------------------------------------------------------------------- %%% @author 0xAX <> %%% @doc Talkerapp transport root supervisor . %%% @end %%%----------------------------------------------------------------------------- -module(talker_app_sup). -behaviour(supervisor). %% API -export([start_link/0, start_talkerapp_client/5]). %% Supervisor callbacks -export([init/1]). %% =================================================================== %% API functions %% =================================================================== start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). %% @doc Start new talkerapp client %% @end -spec start_talkerapp_client(Callback :: pid(), BotNick :: binary(), Room :: binary(), Token :: binary(), RecTimeout :: integer()) -> {ok, Pid :: pid()} | {error, Reason :: term()}. start_talkerapp_client(Callback, BotNick, Room, Token, RecTimeout) -> % Child Child = {talker_app_client, {talker_app_client, start_link, [Callback, BotNick, Room, Token, RecTimeout]}, temporary, 2000, worker, [] }, % run new talkerapp client supervisor:start_child(?MODULE, Child). init([]) -> % init {ok,{{one_for_one, 2, 60}, []}}.
null
https://raw.githubusercontent.com/OtpChatBot/Ybot/5ce05fea0eb9001d1c0ff89702729f4c80743872/src/transport/talkerapp/talker_app_sup.erl
erlang
----------------------------------------------------------------------------- @author 0xAX <> @doc @end ----------------------------------------------------------------------------- API Supervisor callbacks =================================================================== API functions =================================================================== @doc Start new talkerapp client @end Child run new talkerapp client init
Talkerapp transport root supervisor . -module(talker_app_sup). -behaviour(supervisor). -export([start_link/0, start_talkerapp_client/5]). -export([init/1]). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). -spec start_talkerapp_client(Callback :: pid(), BotNick :: binary(), Room :: binary(), Token :: binary(), RecTimeout :: integer()) -> {ok, Pid :: pid()} | {error, Reason :: term()}. start_talkerapp_client(Callback, BotNick, Room, Token, RecTimeout) -> Child = {talker_app_client, {talker_app_client, start_link, [Callback, BotNick, Room, Token, RecTimeout]}, temporary, 2000, worker, [] }, supervisor:start_child(?MODULE, Child). init([]) -> {ok,{{one_for_one, 2, 60}, []}}.
7bb6f672e4714c08826c42ba31d900e6959fddcca7f94b931018bb048931eecc
jserot/lascar
stringable.mli
(**********************************************************************) (* *) LASCAr (* *) Copyright ( c ) 2017 - present , . All rights reserved . (* *) (* This source code is licensed under the license found in the *) (* LICENSE file in the root directory of this source tree. *) (* *) (**********************************************************************) * { 2 String - convertible types } module type T = sig type t val to_string: t -> string end module Pair (M1: T) (M2: T) : sig include T with type t = M1.t * M2.t val mk: M1.t -> M2.t -> t end module Triplet (M1: T) (M2: T) (M3: T) : sig include T with type t = M1.t * M2.t * M3.t val mk: M1.t -> M2.t -> M3.t -> t end
null
https://raw.githubusercontent.com/jserot/lascar/79bd11cd0d47545bccfc3a3571f37af065915c83/src/utils/stringable.mli
ocaml
******************************************************************** This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. ********************************************************************
LASCAr Copyright ( c ) 2017 - present , . All rights reserved . * { 2 String - convertible types } module type T = sig type t val to_string: t -> string end module Pair (M1: T) (M2: T) : sig include T with type t = M1.t * M2.t val mk: M1.t -> M2.t -> t end module Triplet (M1: T) (M2: T) (M3: T) : sig include T with type t = M1.t * M2.t * M3.t val mk: M1.t -> M2.t -> M3.t -> t end
f42fba33bcae704e59ff8511e84b470b6aa047df28aa3106605fdc09f549fbda
cxphoe/SICP-solutions
2.37.rkt
(load "2.36.rkt") (define (dot-product v w) (accumulate + 0 (map * v w))) (define (matrix-*-vector m v) (map (lambda (w) (dot-product v w)) m)) (define (matrix-*-matrix m n) (let ((cols (transpose n))) (map (lambda (x) (matrix-*-vector cols x)) m))) (define (transpose mat) (accumulate-n cons nil mat)) (define x (list (list 1 2 3) (list 4 5 6))) (define y (list (list 1 4) (list 2 5) (list 3 6)))
null
https://raw.githubusercontent.com/cxphoe/SICP-solutions/d35bb688db0320f6efb3b3bde1a14ce21da319bd/Chapter%202-Building%20Abstractions%20with%20Data/2.Hierarchical%20Data%20and%20the%20Closure%20Property/2.37.rkt
racket
(load "2.36.rkt") (define (dot-product v w) (accumulate + 0 (map * v w))) (define (matrix-*-vector m v) (map (lambda (w) (dot-product v w)) m)) (define (matrix-*-matrix m n) (let ((cols (transpose n))) (map (lambda (x) (matrix-*-vector cols x)) m))) (define (transpose mat) (accumulate-n cons nil mat)) (define x (list (list 1 2 3) (list 4 5 6))) (define y (list (list 1 4) (list 2 5) (list 3 6)))
462227394ec0fe62354e72698b112e9b536be69858167f34c7041543495c7a1b
dbuenzli/fmt
fmt.ml
--------------------------------------------------------------------------- Copyright ( c ) 2014 The fmt programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2014 The fmt programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) let invalid_arg' = invalid_arg (* Errors *) let err_str_formatter = "Format.str_formatter can't be set." (* Standard outputs *) let stdout = Format.std_formatter let stderr = Format.err_formatter (* Formatting *) let pf = Format.fprintf let pr = Format.printf let epr = Format.eprintf let str = Format.asprintf let kpf = Format.kfprintf let kstr = Format.kasprintf let failwith fmt = kstr failwith fmt let failwith_notrace fmt = kstr (fun s -> raise_notrace (Failure s)) fmt let invalid_arg fmt = kstr invalid_arg fmt let error fmt = kstr (fun s -> Error s) fmt let error_msg fmt = kstr (fun s -> Error (`Msg s)) fmt Formatters type 'a t = Format.formatter -> 'a -> unit let flush ppf _ = Format.pp_print_flush ppf () let nop fmt ppf = () let any fmt ppf _ = pf ppf fmt let using f pp ppf v = pp ppf (f v) let const pp_v v ppf _ = pp_v ppf v let if' bool pp = if bool then pp else nop let fmt fmt ppf = pf ppf fmt (* Separators *) let cut ppf _ = Format.pp_print_cut ppf () let sp ppf _ = Format.pp_print_space ppf () let sps n ppf _ = Format.pp_print_break ppf n 0 let comma ppf _ = Format.pp_print_string ppf ","; sp ppf () let semi ppf _ = Format.pp_print_string ppf ";"; sp ppf () (* Sequencing *) let iter ?sep:(pp_sep = cut) iter pp_elt ppf v = let is_first = ref true in let pp_elt v = if !is_first then (is_first := false) else pp_sep ppf (); pp_elt ppf v in iter pp_elt v let iter_bindings ?sep:(pp_sep = cut) iter pp_binding ppf v = let is_first = ref true in let pp_binding k v = if !is_first then (is_first := false) else pp_sep ppf (); pp_binding ppf (k, v) in iter pp_binding v let append pp_v0 pp_v1 ppf v = pp_v0 ppf v; pp_v1 ppf v let ( ++ ) = append let concat ?sep pps ppf v = iter ?sep List.iter (fun ppf pp -> pp ppf v) ppf pps (* Boxes *) let box ?(indent = 0) pp_v ppf v = Format.(pp_open_box ppf indent; pp_v ppf v; pp_close_box ppf ()) let hbox pp_v ppf v = Format.(pp_open_hbox ppf (); pp_v ppf v; pp_close_box ppf ()) let vbox ?(indent = 0) pp_v ppf v = Format.(pp_open_vbox ppf indent; pp_v ppf v; pp_close_box ppf ()) let hvbox ?(indent = 0) pp_v ppf v = Format.(pp_open_hvbox ppf indent; pp_v ppf v; pp_close_box ppf ()) let hovbox ?(indent = 0) pp_v ppf v = Format.(pp_open_hovbox ppf indent; pp_v ppf v; pp_close_box ppf ()) (* Brackets *) let surround s1 s2 pp_v ppf v = Format.(pp_print_string ppf s1; pp_v ppf v; pp_print_string ppf s2) let parens pp_v = box ~indent:1 (surround "(" ")" pp_v) let brackets pp_v = box ~indent:1 (surround "[" "]" pp_v) let oxford_brackets pp_v = box ~indent:2 (surround "[|" "|]" pp_v) let braces pp_v = box ~indent:1 (surround "{" "}" pp_v) let quote ?(mark = "\"") pp_v = let pp_mark ppf _ = Format.pp_print_as ppf 1 mark in box ~indent:1 (pp_mark ++ pp_v ++ pp_mark) (* Stdlib types formatters *) let bool = Format.pp_print_bool let int = Format.pp_print_int let nativeint ppf v = pf ppf "%nd" v let int32 ppf v = pf ppf "%ld" v let int64 ppf v = pf ppf "%Ld" v let uint ppf v = pf ppf "%u" v let uint32 ppf v = pf ppf "%lu" v let uint64 ppf v = pf ppf "%Lu" v let unativeint ppf v = pf ppf "%nu" v let char = Format.pp_print_char let string = Format.pp_print_string let buffer ppf b = string ppf (Buffer.contents b) let exn ppf e = string ppf (Printexc.to_string e) let exn_backtrace ppf (e, bt) = let pp_backtrace_str ppf s = let stop = String.length s - 1 (* there's a newline at the end *) in let rec loop left right = if right = stop then string ppf (String.sub s left (right - left)) else if s.[right] <> '\n' then loop left (right + 1) else begin string ppf (String.sub s left (right - left)); cut ppf (); loop (right + 1) (right + 1) end in if s = "" then (string ppf "No backtrace available.") else loop 0 0 in pf ppf "@[<v>Exception: %a@,%a@]" exn e pp_backtrace_str (Printexc.raw_backtrace_to_string bt) let float ppf v = pf ppf "%g" v let round x = floor (x +. 0.5) let round_dfrac d x = if x -. (round x) = 0. then x else (* x is an integer. *) m moves 10 ^ -d to 1 . (floor ((x *. m) +. 0.5)) /. m let round_dsig d x = if x = 0. then 0. else let m = 10. ** (floor (log10 (abs_float x))) in (* to normalize x. *) (round_dfrac d (x /. m)) *. m let float_dfrac d ppf f = pf ppf "%g" (round_dfrac d f) let float_dsig d ppf f = pf ppf "%g" (round_dsig d f) let pair ?sep:(pp_sep = cut) pp_fst pp_snd ppf (fst, snd) = pp_fst ppf fst; pp_sep ppf (); pp_snd ppf snd let option ?none:(pp_none = nop) pp_v ppf = function | None -> pp_none ppf () | Some v -> pp_v ppf v let result ~ok ~error ppf = function | Ok v -> ok ppf v | Error e -> error ppf e let list ?sep pp_elt = iter ?sep List.iter pp_elt let array ?sep pp_elt = iter ?sep Array.iter pp_elt let seq ?sep pp_elt = iter ?sep Seq.iter pp_elt let hashtbl ?sep pp_binding = iter_bindings ?sep Hashtbl.iter pp_binding let queue ?sep pp_elt = iter Queue.iter pp_elt let stack ?sep pp_elt = iter Stack.iter pp_elt (* Stdlib type dumpers *) module Dump = struct (* Stdlib types *) let sig_names = Sys.[ sigabrt, "SIGABRT"; sigalrm, "SIGALRM"; sigfpe, "SIGFPE"; sighup, "SIGHUP"; sigill, "SIGILL"; sigint, "SIGINT"; sigkill, "SIGKILL"; sigpipe, "SIGPIPE"; sigquit, "SIGQUIT"; sigsegv, "SIGSEGV"; sigterm, "SIGTERM"; sigusr1, "SIGUSR1"; sigusr2, "SIGUSR2"; sigchld, "SIGCHLD"; sigcont, "SIGCONT"; sigstop, "SIGSTOP"; sigtstp, "SIGTSTP"; sigttin, "SIGTTIN"; sigttou, "SIGTTOU"; sigvtalrm, "SIGVTALRM"; sigprof, "SIGPROF"; sigbus, "SIGBUS"; sigpoll, "SIGPOLL"; sigsys, "SIGSYS"; sigtrap, "SIGTRAP"; sigurg, "SIGURG"; sigxcpu, "SIGXCPU"; sigxfsz, "SIGXFSZ"; ] let signal ppf s = match List.assq_opt s sig_names with | Some name -> string ppf name | None -> pf ppf "SIG(%d)" s let uchar ppf u = pf ppf "U+%04X" (Uchar.to_int u) let string ppf s = pf ppf "%S" s let pair pp_fst pp_snd = parens (using fst (box pp_fst) ++ comma ++ using snd (box pp_snd)) let option pp_v ppf = function | None -> pf ppf "None" | Some v -> pf ppf "@[<2>Some@ @[%a@]@]" pp_v v let result ~ok ~error ppf = function | Ok v -> pf ppf "@[<2>Ok@ @[%a@]@]" ok v | Error e -> pf ppf "@[<2>Error@ @[%a@]@]" error e (* Sequencing *) let iter iter_f pp_name pp_elt = let pp_v = iter ~sep:sp iter_f (box pp_elt) in parens (pp_name ++ sp ++ pp_v) let iter_bindings iter_f pp_name pp_k pp_v = let pp_v = iter_bindings ~sep:sp iter_f (pair pp_k pp_v) in parens (pp_name ++ sp ++ pp_v) (* Stdlib data structures *) let list pp_elt = brackets (list ~sep:semi (box pp_elt)) let array pp_elt = oxford_brackets (array ~sep:semi (box pp_elt)) let seq pp_elt = brackets (seq ~sep:semi (box pp_elt)) let hashtbl pp_k pp_v = iter_bindings Hashtbl.iter (any "hashtbl") pp_k pp_v let stack pp_elt = iter Stack.iter (any "stack") pp_elt let queue pp_elt = iter Queue.iter (any "queue") pp_elt Records let field ?(label = string) l prj pp_v ppf v = pf ppf "@[<1>%a =@ %a@]" label l pp_v (prj v) let record pps = box ~indent:2 (surround "{ " " }" @@ vbox (concat ~sep:(any ";@,") pps)) end (* Magnitudes *) let ilog10 x = let rec loop p x = if x = 0 then p else loop (p + 1) (x / 10) in loop (-1) x let ipow10 n = let rec loop acc n = if n = 0 then acc else loop (acc * 10) (n - 1) in loop 1 n let si_symb_max = 16 let si_symb = [| "y"; "z"; "a"; "f"; "p"; "n"; "u"; "m"; ""; "k"; "M"; "G"; "T"; "P"; "E"; "Z"; "Y"|] let rec pp_at_factor ~scale u symb factor ppf s = let m = s / factor in let n = s mod factor in match m with | m when m >= 100 -> (* No fractional digit *) let m_up = if n > 0 then m + 1 else m in if m_up >= 1000 then si_size ~scale u ppf (m_up * factor) else pf ppf "%d%s%s" m_up symb u One fractional digit w.o . trailing 0 let f_factor = factor / 10 in let f_m = n / f_factor in let f_n = n mod f_factor in let f_m_up = if f_n > 0 then f_m + 1 else f_m in begin match f_m_up with | 0 -> pf ppf "%d%s%s" m symb u | f when f >= 10 -> si_size ~scale u ppf (m * factor + f * f_factor) | f -> pf ppf "%d.%d%s%s" m f symb u end Two or zero fractional digits w.o . trailing 0 let f_factor = factor / 100 in let f_m = n / f_factor in let f_n = n mod f_factor in let f_m_up = if f_n > 0 then f_m + 1 else f_m in match f_m_up with | 0 -> pf ppf "%d%s%s" m symb u | f when f >= 100 -> si_size ~scale u ppf (m * factor + f * f_factor) | f when f mod 10 = 0 -> pf ppf "%d.%d%s%s" m (f / 10) symb u | f -> pf ppf "%d.%02d%s%s" m f symb u and si_size ~scale u ppf s = match scale < -8 || scale > 8 with | true -> invalid_arg "~scale is %d, must be in [-8;8]" scale | false -> let pow_div_3 = if s = 0 then 0 else (ilog10 s / 3) in let symb = (scale + 8) + pow_div_3 in let symb, factor = match symb > si_symb_max with | true -> si_symb_max, ipow10 ((8 - scale) * 3) | false -> symb, ipow10 (pow_div_3 * 3) in if factor = 1 then pf ppf "%d%s%s" s si_symb.(symb) u else pp_at_factor ~scale u si_symb.(symb) factor ppf s let byte_size ppf s = si_size ~scale:0 "B" ppf s let bi_byte_size ppf s = (* XXX we should get rid of this. *) let _pp_byte_size k i ppf s = let pp_frac = float_dfrac 1 in let div_round_up m n = (m + n - 1) / n in let float = float_of_int in if s < k then pf ppf "%dB" s else let m = k * k in if s < m then begin let kstr = if i = "" then "k" (* SI *) else "K" (* IEC *) in let sk = s / k in if sk < 10 then pf ppf "%a%s%sB" pp_frac (float s /. float k) kstr i else pf ppf "%d%s%sB" (div_round_up s k) kstr i end else let g = k * m in if s < g then begin let sm = s / m in if sm < 10 then pf ppf "%aM%sB" pp_frac (float s /. float m) i else pf ppf "%dM%sB" (div_round_up s m) i end else let t = k * g in if s < t then begin let sg = s / g in if sg < 10 then pf ppf "%aG%sB" pp_frac (float s /. float g) i else pf ppf "%dG%sB" (div_round_up s g) i end else let p = k * t in if s < p then begin let st = s / t in if st < 10 then pf ppf "%aT%sB" pp_frac (float s /. float t) i else pf ppf "%dT%sB" (div_round_up s t) i end else begin let sp = s / p in if sp < 10 then pf ppf "%aP%sB" pp_frac (float s /. float p) i else pf ppf "%dP%sB" (div_round_up s p) i end in _pp_byte_size 1024 "i" ppf s XXX From 4.08 on use Int64.unsigned _ * See Hacker 's Delight for the implementation of these unsigned _ * funs See Hacker's Delight for the implementation of these unsigned_* funs *) let unsigned_compare x0 x1 = Int64.(compare (sub x0 min_int) (sub x1 min_int)) let unsigned_div n d = match d < Int64.zero with | true -> if unsigned_compare n d < 0 then Int64.zero else Int64.one | false -> let q = Int64.(shift_left (div (shift_right_logical n 1) d) 1) in let r = Int64.(sub n (mul q d)) in if unsigned_compare r d >= 0 then Int64.succ q else q let unsigned_rem n d = Int64.(sub n (mul (unsigned_div n d) d)) let us_span = 1_000L let ms_span = 1_000_000L let sec_span = 1_000_000_000L let min_span = 60_000_000_000L let hour_span = 3600_000_000_000L let day_span = 86_400_000_000_000L let year_span = 31_557_600_000_000_000L let rec pp_si_span unit_str si_unit si_higher_unit ppf span = let geq x y = unsigned_compare x y >= 0 in let m = unsigned_div span si_unit in let n = unsigned_rem span si_unit in match m with | m when geq m 100L -> (* No fractional digit *) let m_up = if Int64.equal n 0L then m else Int64.succ m in let span' = Int64.mul m_up si_unit in if geq span' si_higher_unit then uint64_ns_span ppf span' else pf ppf "%Ld%s" m_up unit_str One fractional digit w.o . trailing zero let f_factor = unsigned_div si_unit 10L in let f_m = unsigned_div n f_factor in let f_n = unsigned_rem n f_factor in let f_m_up = if Int64.equal f_n 0L then f_m else Int64.succ f_m in begin match f_m_up with | 0L -> pf ppf "%Ld%s" m unit_str | f when geq f 10L -> uint64_ns_span ppf Int64.(add (mul m si_unit) (mul f f_factor)) | f -> pf ppf "%Ld.%Ld%s" m f unit_str end Two or zero fractional digits w.o . trailing zero let f_factor = unsigned_div si_unit 100L in let f_m = unsigned_div n f_factor in let f_n = unsigned_rem n f_factor in let f_m_up = if Int64.equal f_n 0L then f_m else Int64.succ f_m in match f_m_up with | 0L -> pf ppf "%Ld%s" m unit_str | f when geq f 100L -> uint64_ns_span ppf Int64.(add (mul m si_unit) (mul f f_factor)) | f when Int64.equal (Int64.rem f 10L) 0L -> pf ppf "%Ld.%Ld%s" m (Int64.div f 10L) unit_str | f -> pf ppf "%Ld.%02Ld%s" m f unit_str and pp_non_si unit_str unit unit_lo_str unit_lo unit_lo_size ppf span = let geq x y = unsigned_compare x y >= 0 in let m = unsigned_div span unit in let n = unsigned_rem span unit in if Int64.equal n 0L then pf ppf "%Ld%s" m unit_str else let f_m = unsigned_div n unit_lo in let f_n = unsigned_rem n unit_lo in let f_m_up = if Int64.equal f_n 0L then f_m else Int64.succ f_m in match f_m_up with | f when geq f unit_lo_size -> uint64_ns_span ppf Int64.(add (mul m unit) (mul f unit_lo)) | f -> pf ppf "%Ld%s%Ld%s" m unit_str f unit_lo_str and uint64_ns_span ppf span = let geq x y = unsigned_compare x y >= 0 in let lt x y = unsigned_compare x y = -1 in match span with | s when lt s us_span -> pf ppf "%Ldns" s | s when lt s ms_span -> pp_si_span "us" us_span ms_span ppf s | s when lt s sec_span -> pp_si_span "ms" ms_span sec_span ppf s | s when lt s min_span -> pp_si_span "s" sec_span min_span ppf s | s when lt s hour_span -> pp_non_si "min" min_span "s" sec_span 60L ppf s | s when lt s day_span -> pp_non_si "h" hour_span "min" min_span 60L ppf s | s when lt s year_span -> pp_non_si "d" day_span "h" hour_span 24L ppf s | s -> let m = unsigned_div s year_span in let n = unsigned_rem s year_span in if Int64.equal n 0L then pf ppf "%Lda" m else let f_m = unsigned_div n day_span in let f_n = unsigned_rem n day_span in let f_m_up = if Int64.equal f_n 0L then f_m else Int64.succ f_m in match f_m_up with | f when geq f 366L -> pf ppf "%Lda" (Int64.succ m) | f -> pf ppf "%Lda%Ldd" m f (* Binary formatting *) type 'a vec = int * (int -> 'a) let iter_vec f (n, get) = for i = 0 to n - 1 do f i (get i) done let vec ?sep = iter_bindings ?sep iter_vec let on_string = using String.(fun s -> length s, get s) let on_bytes = using Bytes.(fun b -> length b, get b) let sub_vecs w (n, get) = (n - 1) / w + 1, fun j -> let off = w * j in min w (n - off), fun i -> get (i + off) let prefix0x = [ 0xf , fmt "%01x"; 0xff , fmt "%02x"; 0xfff , fmt "%03x"; 0xffff , fmt "%04x"; 0xfffff , fmt "%05x"; 0xffffff , fmt "%06x"; 0xfffffff , fmt "%07x"; ] let padded0x ~max = match List.find_opt (fun (x, _) -> max <= x) prefix0x with | Some (_, pp) -> pp | None -> fmt "%08x" let ascii ?(w = 0) ?(subst = const char '.') () ppf (n, _ as v) = let pp_char ppf (_, c) = if '\x20' <= c && c < '\x7f' then char ppf c else subst ppf () in vec pp_char ppf v; if n < w then sps (w - n) ppf () let octets ?(w = 0) ?(sep = sp) () ppf (n, _ as v) = let pp_sep ppf i = if i > 0 && i mod 2 = 0 then sep ppf () in let pp_char ppf (i, c) = pp_sep ppf i; pf ppf "%02x" (Char.code c) in vec ~sep:nop pp_char ppf v; for i = n to w - 1 do pp_sep ppf i; sps 2 ppf () done let addresses ?addr ?(w = 16) pp_vec ppf (n, _ as v) = let addr = match addr with | Some pp -> pp | _ -> padded0x ~max:(((n - 1) / w) * w) ++ const string ": " in let pp_sub ppf (i, sub) = addr ppf (i * w); box pp_vec ppf sub in vbox (vec pp_sub) ppf (sub_vecs w v) let hex ?(w = 16) () = addresses ~w ((octets ~w () |> box) ++ sps 2 ++ (ascii ~w () |> box)) (* Text and lines *) let is_nl c = c = '\n' let is_nl_or_sp c = is_nl c || c = ' ' let is_white = function ' ' | '\t' .. '\r' -> true | _ -> false let not_white c = not (is_white c) let not_white_or_nl c = is_nl c || not_white c let rec stop_at sat ~start ~max s = if start > max then start else if sat s.[start] then start else stop_at sat ~start:(start + 1) ~max s let sub s start stop ~max = if start = stop then "" else if start = 0 && stop > max then s else String.sub s start (stop - start) let words ppf s = let max = String.length s - 1 in let rec loop start s = match stop_at is_white ~start ~max s with | stop when stop > max -> Format.pp_print_string ppf (sub s start stop ~max) | stop -> Format.pp_print_string ppf (sub s start stop ~max); match stop_at not_white ~start:stop ~max s with | stop when stop > max -> () | stop -> Format.pp_print_space ppf (); loop stop s in let start = stop_at not_white ~start:0 ~max s in if start > max then () else loop start s let paragraphs ppf s = let max = String.length s - 1 in let rec loop start s = match stop_at is_white ~start ~max s with | stop when stop > max -> Format.pp_print_string ppf (sub s start stop ~max) | stop -> Format.pp_print_string ppf (sub s start stop ~max); match stop_at not_white_or_nl ~start:stop ~max s with | stop when stop > max -> () | stop -> if s.[stop] <> '\n' then (Format.pp_print_space ppf (); loop stop s) else match stop_at not_white_or_nl ~start:(stop + 1) ~max s with | stop when stop > max -> () | stop -> if s.[stop] <> '\n' then (Format.pp_print_space ppf (); loop stop s) else match stop_at not_white ~start:(stop + 1) ~max s with | stop when stop > max -> () | stop -> Format.pp_force_newline ppf (); Format.pp_force_newline ppf (); loop stop s in let start = stop_at not_white ~start:0 ~max s in if start > max then () else loop start s let text ppf s = let max = String.length s - 1 in let rec loop start s = match stop_at is_nl_or_sp ~start ~max s with | stop when stop > max -> Format.pp_print_string ppf (sub s start stop ~max) | stop -> Format.pp_print_string ppf (sub s start stop ~max); begin match s.[stop] with | ' ' -> Format.pp_print_space ppf () | '\n' -> Format.pp_force_newline ppf () | _ -> assert false end; loop (stop + 1) s in loop 0 s let lines ppf s = let max = String.length s - 1 in let rec loop start s = match stop_at is_nl ~start ~max s with | stop when stop > max -> Format.pp_print_string ppf (sub s start stop ~max) | stop -> Format.pp_print_string ppf (sub s start stop ~max); Format.pp_force_newline ppf (); loop (stop + 1) s in loop 0 s let truncated ~max ppf s = match String.length s <= max with | true -> Format.pp_print_string ppf s | false -> for i = 0 to max - 4 do Format.pp_print_char ppf s.[i] done; Format.pp_print_string ppf "..." let text_loc ppf ((l0, c0), (l1, c1)) = if (l0 : int) == (l1 : int) && (c0 : int) == (c1 : int) then pf ppf "%d.%d" l0 c0 else pf ppf "%d.%d-%d.%d" l0 c0 l1 c1 HCI fragments let one_of ?(empty = nop) pp_v ppf = function | [] -> empty ppf () | [v] -> pp_v ppf v | [v0; v1] -> pf ppf "@[either %a or@ %a@]" pp_v v0 pp_v v1 | _ :: _ as vs -> let rec loop ppf = function | [v] -> pf ppf "or@ %a" pp_v v | v :: vs -> pf ppf "%a,@ " pp_v v; loop ppf vs | [] -> assert false in pf ppf "@[one@ of@ %a@]" loop vs let did_you_mean ?(pre = any "Unknown") ?(post = nop) ~kind pp_v ppf (v, hints) = match hints with | [] -> pf ppf "@[%a %s %a%a.@]" pre () kind pp_v v post () | hints -> pf ppf "@[%a %s %a%a.@ Did you mean %a ?@]" pre () kind pp_v v post () (one_of pp_v) hints (* Conditional UTF-8 and styled formatting. *) module Imap = Map.Make (Int) type 'a attr = int * ('a -> string) * (string -> 'a) let id = ref 0 let attr (type a) enc dec = incr id; (!id, enc, dec) type Format.stag += | Fmt_store_get : 'a attr -> Format.stag | Fmt_store_set : 'a attr * 'a -> Format.stag let store () = let s = ref Imap.empty in fun ~other -> function | Fmt_store_get (id, _, _) -> Option.value ~default:"" (Imap.find_opt id !s) | Fmt_store_set ((id, enc, _), v) -> s := Imap.add id (enc v) !s; "ok" | stag -> other stag let setup_store ppf = let funs = Format.pp_get_formatter_stag_functions ppf () in let mark_open_stag = store () ~other:funs.mark_open_stag in Format.pp_set_formatter_stag_functions ppf { funs with mark_open_stag } let store_op op ppf = let funs = Format.pp_get_formatter_stag_functions ppf () in funs.mark_open_stag op let get (_, _, dec as attr) ppf = match store_op (Fmt_store_get attr) ppf with | "" -> None | s -> Some (dec s) let rec set attr v ppf = match store_op (Fmt_store_set (attr, v)) ppf with | "ok" -> () | _ -> setup_store ppf; set attr v ppf let def x = function Some y -> y | _ -> x let utf_8_attr = let enc = function true -> "t" | false -> "f" in let dec = function "t" -> true | "f" -> false | _ -> assert false in attr enc dec let utf_8 ppf = get utf_8_attr ppf |> def true let set_utf_8 ppf x = set utf_8_attr x ppf type style_renderer = [ `Ansi_tty | `None ] let style_renderer_attr = let enc = function `Ansi_tty -> "A" | `None -> "N" in let dec = function "A" -> `Ansi_tty | "N" -> `None | _ -> assert false in attr enc dec let style_renderer ppf = get style_renderer_attr ppf |> def `None let set_style_renderer ppf x = set style_renderer_attr x ppf let with_buffer ?like buf = let ppf = Format.formatter_of_buffer buf in N.B. this does slighty more it also makes buf use other installed semantic tag actions . semantic tag actions. *) match like with | None -> ppf | Some like -> let funs = Format.pp_get_formatter_stag_functions like () in Format.pp_set_formatter_stag_functions ppf funs; ppf let str_like ppf fmt = let buf = Buffer.create 64 in let bppf = with_buffer ~like:ppf buf in let flush ppf = Format.pp_print_flush ppf (); let s = Buffer.contents buf in Buffer.reset buf; s in Format.kfprintf flush bppf fmt (* Conditional UTF-8 formatting *) let if_utf_8 pp_u pp = fun ppf v -> (if utf_8 ppf then pp_u else pp) ppf v (* Styled formatting *) type color = [ `Black | `Blue | `Cyan | `Green | `Magenta | `Red | `White | `Yellow ] type style = [ `None | `Bold | `Faint | `Italic | `Underline | `Reverse | `Fg of [ color | `Hi of color ] | `Bg of [ color | `Hi of color ] | color (** deprecated *) ] let ansi_style_code = function | `Bold -> "1" | `Faint -> "2" | `Italic -> "3" | `Underline -> "4" | `Reverse -> "7" | `Fg `Black -> "30" | `Fg `Red -> "31" | `Fg `Green -> "32" | `Fg `Yellow -> "33" | `Fg `Blue -> "34" | `Fg `Magenta -> "35" | `Fg `Cyan -> "36" | `Fg `White -> "37" | `Bg `Black -> "40" | `Bg `Red -> "41" | `Bg `Green -> "42" | `Bg `Yellow -> "43" | `Bg `Blue -> "44" | `Bg `Magenta -> "45" | `Bg `Cyan -> "46" | `Bg `White -> "47" | `Fg (`Hi `Black) -> "90" | `Fg (`Hi `Red) -> "91" | `Fg (`Hi `Green) -> "92" | `Fg (`Hi `Yellow) -> "93" | `Fg (`Hi `Blue) -> "94" | `Fg (`Hi `Magenta) -> "95" | `Fg (`Hi `Cyan) -> "96" | `Fg (`Hi `White) -> "97" | `Bg (`Hi `Black) -> "100" | `Bg (`Hi `Red) -> "101" | `Bg (`Hi `Green) -> "102" | `Bg (`Hi `Yellow) -> "103" | `Bg (`Hi `Blue) -> "104" | `Bg (`Hi `Magenta) -> "105" | `Bg (`Hi `Cyan) -> "106" | `Bg (`Hi `White) -> "107" | `None -> "0" (* deprecated *) | `Black -> "30" | `Red -> "31" | `Green -> "32" | `Yellow -> "33" | `Blue -> "34" | `Magenta -> "35" | `Cyan -> "36" | `White -> "37" let pp_sgr ppf style = Format.pp_print_as ppf 0 "\027["; Format.pp_print_as ppf 0 style; Format.pp_print_as ppf 0 "m" let curr_style = attr Fun.id Fun.id let styled style pp_v ppf v = match style_renderer ppf with | `None -> pp_v ppf v | `Ansi_tty -> let prev = match get curr_style ppf with | None -> let zero = "0" in set curr_style zero ppf; zero | Some s -> s in let here = ansi_style_code style in let curr = match style with | `None -> here | _ -> String.concat ";" [prev; here] in let finally () = set curr_style prev ppf in set curr_style curr ppf; Fun.protect ~finally @@ fun () -> pp_sgr ppf here; pp_v ppf v; pp_sgr ppf prev Records let id = Fun.id let label = styled (`Fg `Yellow) string let field ?(label = label) ?(sep = any ":@ ") l prj pp_v ppf v = pf ppf "@[<1>%a%a%a@]" label l sep () pp_v (prj v) let record ?(sep = cut) pps = vbox (concat ~sep pps) (* Converting with string converters. *) let of_to_string f ppf v = string ppf (f v) let to_to_string pp_v v = str "%a" pp_v v (* Deprecated *) let strf = str let kstrf = kstr let strf_like = str_like let always = any let unit = any let prefix pp_p pp_v ppf v = pp_p ppf (); pp_v ppf v let suffix pp_s pp_v ppf v = pp_v ppf v; pp_s ppf () let styled_unit style fmt = styled style (any fmt) --------------------------------------------------------------------------- Copyright ( c ) 2014 The fmt programmers Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2014 The fmt programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/dbuenzli/fmt/9db1a3c058973123324e374d751f452a8e434505/src/fmt.ml
ocaml
Errors Standard outputs Formatting Separators Sequencing Boxes Brackets Stdlib types formatters there's a newline at the end x is an integer. to normalize x. Stdlib type dumpers Stdlib types Sequencing Stdlib data structures Magnitudes No fractional digit XXX we should get rid of this. SI IEC No fractional digit Binary formatting Text and lines Conditional UTF-8 and styled formatting. Conditional UTF-8 formatting Styled formatting * deprecated deprecated Converting with string converters. Deprecated
--------------------------------------------------------------------------- Copyright ( c ) 2014 The fmt programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2014 The fmt programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) let invalid_arg' = invalid_arg let err_str_formatter = "Format.str_formatter can't be set." let stdout = Format.std_formatter let stderr = Format.err_formatter let pf = Format.fprintf let pr = Format.printf let epr = Format.eprintf let str = Format.asprintf let kpf = Format.kfprintf let kstr = Format.kasprintf let failwith fmt = kstr failwith fmt let failwith_notrace fmt = kstr (fun s -> raise_notrace (Failure s)) fmt let invalid_arg fmt = kstr invalid_arg fmt let error fmt = kstr (fun s -> Error s) fmt let error_msg fmt = kstr (fun s -> Error (`Msg s)) fmt Formatters type 'a t = Format.formatter -> 'a -> unit let flush ppf _ = Format.pp_print_flush ppf () let nop fmt ppf = () let any fmt ppf _ = pf ppf fmt let using f pp ppf v = pp ppf (f v) let const pp_v v ppf _ = pp_v ppf v let if' bool pp = if bool then pp else nop let fmt fmt ppf = pf ppf fmt let cut ppf _ = Format.pp_print_cut ppf () let sp ppf _ = Format.pp_print_space ppf () let sps n ppf _ = Format.pp_print_break ppf n 0 let comma ppf _ = Format.pp_print_string ppf ","; sp ppf () let semi ppf _ = Format.pp_print_string ppf ";"; sp ppf () let iter ?sep:(pp_sep = cut) iter pp_elt ppf v = let is_first = ref true in let pp_elt v = if !is_first then (is_first := false) else pp_sep ppf (); pp_elt ppf v in iter pp_elt v let iter_bindings ?sep:(pp_sep = cut) iter pp_binding ppf v = let is_first = ref true in let pp_binding k v = if !is_first then (is_first := false) else pp_sep ppf (); pp_binding ppf (k, v) in iter pp_binding v let append pp_v0 pp_v1 ppf v = pp_v0 ppf v; pp_v1 ppf v let ( ++ ) = append let concat ?sep pps ppf v = iter ?sep List.iter (fun ppf pp -> pp ppf v) ppf pps let box ?(indent = 0) pp_v ppf v = Format.(pp_open_box ppf indent; pp_v ppf v; pp_close_box ppf ()) let hbox pp_v ppf v = Format.(pp_open_hbox ppf (); pp_v ppf v; pp_close_box ppf ()) let vbox ?(indent = 0) pp_v ppf v = Format.(pp_open_vbox ppf indent; pp_v ppf v; pp_close_box ppf ()) let hvbox ?(indent = 0) pp_v ppf v = Format.(pp_open_hvbox ppf indent; pp_v ppf v; pp_close_box ppf ()) let hovbox ?(indent = 0) pp_v ppf v = Format.(pp_open_hovbox ppf indent; pp_v ppf v; pp_close_box ppf ()) let surround s1 s2 pp_v ppf v = Format.(pp_print_string ppf s1; pp_v ppf v; pp_print_string ppf s2) let parens pp_v = box ~indent:1 (surround "(" ")" pp_v) let brackets pp_v = box ~indent:1 (surround "[" "]" pp_v) let oxford_brackets pp_v = box ~indent:2 (surround "[|" "|]" pp_v) let braces pp_v = box ~indent:1 (surround "{" "}" pp_v) let quote ?(mark = "\"") pp_v = let pp_mark ppf _ = Format.pp_print_as ppf 1 mark in box ~indent:1 (pp_mark ++ pp_v ++ pp_mark) let bool = Format.pp_print_bool let int = Format.pp_print_int let nativeint ppf v = pf ppf "%nd" v let int32 ppf v = pf ppf "%ld" v let int64 ppf v = pf ppf "%Ld" v let uint ppf v = pf ppf "%u" v let uint32 ppf v = pf ppf "%lu" v let uint64 ppf v = pf ppf "%Lu" v let unativeint ppf v = pf ppf "%nu" v let char = Format.pp_print_char let string = Format.pp_print_string let buffer ppf b = string ppf (Buffer.contents b) let exn ppf e = string ppf (Printexc.to_string e) let exn_backtrace ppf (e, bt) = let pp_backtrace_str ppf s = let rec loop left right = if right = stop then string ppf (String.sub s left (right - left)) else if s.[right] <> '\n' then loop left (right + 1) else begin string ppf (String.sub s left (right - left)); cut ppf (); loop (right + 1) (right + 1) end in if s = "" then (string ppf "No backtrace available.") else loop 0 0 in pf ppf "@[<v>Exception: %a@,%a@]" exn e pp_backtrace_str (Printexc.raw_backtrace_to_string bt) let float ppf v = pf ppf "%g" v let round x = floor (x +. 0.5) let round_dfrac d x = m moves 10 ^ -d to 1 . (floor ((x *. m) +. 0.5)) /. m let round_dsig d x = if x = 0. then 0. else (round_dfrac d (x /. m)) *. m let float_dfrac d ppf f = pf ppf "%g" (round_dfrac d f) let float_dsig d ppf f = pf ppf "%g" (round_dsig d f) let pair ?sep:(pp_sep = cut) pp_fst pp_snd ppf (fst, snd) = pp_fst ppf fst; pp_sep ppf (); pp_snd ppf snd let option ?none:(pp_none = nop) pp_v ppf = function | None -> pp_none ppf () | Some v -> pp_v ppf v let result ~ok ~error ppf = function | Ok v -> ok ppf v | Error e -> error ppf e let list ?sep pp_elt = iter ?sep List.iter pp_elt let array ?sep pp_elt = iter ?sep Array.iter pp_elt let seq ?sep pp_elt = iter ?sep Seq.iter pp_elt let hashtbl ?sep pp_binding = iter_bindings ?sep Hashtbl.iter pp_binding let queue ?sep pp_elt = iter Queue.iter pp_elt let stack ?sep pp_elt = iter Stack.iter pp_elt module Dump = struct let sig_names = Sys.[ sigabrt, "SIGABRT"; sigalrm, "SIGALRM"; sigfpe, "SIGFPE"; sighup, "SIGHUP"; sigill, "SIGILL"; sigint, "SIGINT"; sigkill, "SIGKILL"; sigpipe, "SIGPIPE"; sigquit, "SIGQUIT"; sigsegv, "SIGSEGV"; sigterm, "SIGTERM"; sigusr1, "SIGUSR1"; sigusr2, "SIGUSR2"; sigchld, "SIGCHLD"; sigcont, "SIGCONT"; sigstop, "SIGSTOP"; sigtstp, "SIGTSTP"; sigttin, "SIGTTIN"; sigttou, "SIGTTOU"; sigvtalrm, "SIGVTALRM"; sigprof, "SIGPROF"; sigbus, "SIGBUS"; sigpoll, "SIGPOLL"; sigsys, "SIGSYS"; sigtrap, "SIGTRAP"; sigurg, "SIGURG"; sigxcpu, "SIGXCPU"; sigxfsz, "SIGXFSZ"; ] let signal ppf s = match List.assq_opt s sig_names with | Some name -> string ppf name | None -> pf ppf "SIG(%d)" s let uchar ppf u = pf ppf "U+%04X" (Uchar.to_int u) let string ppf s = pf ppf "%S" s let pair pp_fst pp_snd = parens (using fst (box pp_fst) ++ comma ++ using snd (box pp_snd)) let option pp_v ppf = function | None -> pf ppf "None" | Some v -> pf ppf "@[<2>Some@ @[%a@]@]" pp_v v let result ~ok ~error ppf = function | Ok v -> pf ppf "@[<2>Ok@ @[%a@]@]" ok v | Error e -> pf ppf "@[<2>Error@ @[%a@]@]" error e let iter iter_f pp_name pp_elt = let pp_v = iter ~sep:sp iter_f (box pp_elt) in parens (pp_name ++ sp ++ pp_v) let iter_bindings iter_f pp_name pp_k pp_v = let pp_v = iter_bindings ~sep:sp iter_f (pair pp_k pp_v) in parens (pp_name ++ sp ++ pp_v) let list pp_elt = brackets (list ~sep:semi (box pp_elt)) let array pp_elt = oxford_brackets (array ~sep:semi (box pp_elt)) let seq pp_elt = brackets (seq ~sep:semi (box pp_elt)) let hashtbl pp_k pp_v = iter_bindings Hashtbl.iter (any "hashtbl") pp_k pp_v let stack pp_elt = iter Stack.iter (any "stack") pp_elt let queue pp_elt = iter Queue.iter (any "queue") pp_elt Records let field ?(label = string) l prj pp_v ppf v = pf ppf "@[<1>%a =@ %a@]" label l pp_v (prj v) let record pps = box ~indent:2 (surround "{ " " }" @@ vbox (concat ~sep:(any ";@,") pps)) end let ilog10 x = let rec loop p x = if x = 0 then p else loop (p + 1) (x / 10) in loop (-1) x let ipow10 n = let rec loop acc n = if n = 0 then acc else loop (acc * 10) (n - 1) in loop 1 n let si_symb_max = 16 let si_symb = [| "y"; "z"; "a"; "f"; "p"; "n"; "u"; "m"; ""; "k"; "M"; "G"; "T"; "P"; "E"; "Z"; "Y"|] let rec pp_at_factor ~scale u symb factor ppf s = let m = s / factor in let n = s mod factor in match m with let m_up = if n > 0 then m + 1 else m in if m_up >= 1000 then si_size ~scale u ppf (m_up * factor) else pf ppf "%d%s%s" m_up symb u One fractional digit w.o . trailing 0 let f_factor = factor / 10 in let f_m = n / f_factor in let f_n = n mod f_factor in let f_m_up = if f_n > 0 then f_m + 1 else f_m in begin match f_m_up with | 0 -> pf ppf "%d%s%s" m symb u | f when f >= 10 -> si_size ~scale u ppf (m * factor + f * f_factor) | f -> pf ppf "%d.%d%s%s" m f symb u end Two or zero fractional digits w.o . trailing 0 let f_factor = factor / 100 in let f_m = n / f_factor in let f_n = n mod f_factor in let f_m_up = if f_n > 0 then f_m + 1 else f_m in match f_m_up with | 0 -> pf ppf "%d%s%s" m symb u | f when f >= 100 -> si_size ~scale u ppf (m * factor + f * f_factor) | f when f mod 10 = 0 -> pf ppf "%d.%d%s%s" m (f / 10) symb u | f -> pf ppf "%d.%02d%s%s" m f symb u and si_size ~scale u ppf s = match scale < -8 || scale > 8 with | true -> invalid_arg "~scale is %d, must be in [-8;8]" scale | false -> let pow_div_3 = if s = 0 then 0 else (ilog10 s / 3) in let symb = (scale + 8) + pow_div_3 in let symb, factor = match symb > si_symb_max with | true -> si_symb_max, ipow10 ((8 - scale) * 3) | false -> symb, ipow10 (pow_div_3 * 3) in if factor = 1 then pf ppf "%d%s%s" s si_symb.(symb) u else pp_at_factor ~scale u si_symb.(symb) factor ppf s let byte_size ppf s = si_size ~scale:0 "B" ppf s let bi_byte_size ppf s = let _pp_byte_size k i ppf s = let pp_frac = float_dfrac 1 in let div_round_up m n = (m + n - 1) / n in let float = float_of_int in if s < k then pf ppf "%dB" s else let m = k * k in if s < m then begin let sk = s / k in if sk < 10 then pf ppf "%a%s%sB" pp_frac (float s /. float k) kstr i else pf ppf "%d%s%sB" (div_round_up s k) kstr i end else let g = k * m in if s < g then begin let sm = s / m in if sm < 10 then pf ppf "%aM%sB" pp_frac (float s /. float m) i else pf ppf "%dM%sB" (div_round_up s m) i end else let t = k * g in if s < t then begin let sg = s / g in if sg < 10 then pf ppf "%aG%sB" pp_frac (float s /. float g) i else pf ppf "%dG%sB" (div_round_up s g) i end else let p = k * t in if s < p then begin let st = s / t in if st < 10 then pf ppf "%aT%sB" pp_frac (float s /. float t) i else pf ppf "%dT%sB" (div_round_up s t) i end else begin let sp = s / p in if sp < 10 then pf ppf "%aP%sB" pp_frac (float s /. float p) i else pf ppf "%dP%sB" (div_round_up s p) i end in _pp_byte_size 1024 "i" ppf s XXX From 4.08 on use Int64.unsigned _ * See Hacker 's Delight for the implementation of these unsigned _ * funs See Hacker's Delight for the implementation of these unsigned_* funs *) let unsigned_compare x0 x1 = Int64.(compare (sub x0 min_int) (sub x1 min_int)) let unsigned_div n d = match d < Int64.zero with | true -> if unsigned_compare n d < 0 then Int64.zero else Int64.one | false -> let q = Int64.(shift_left (div (shift_right_logical n 1) d) 1) in let r = Int64.(sub n (mul q d)) in if unsigned_compare r d >= 0 then Int64.succ q else q let unsigned_rem n d = Int64.(sub n (mul (unsigned_div n d) d)) let us_span = 1_000L let ms_span = 1_000_000L let sec_span = 1_000_000_000L let min_span = 60_000_000_000L let hour_span = 3600_000_000_000L let day_span = 86_400_000_000_000L let year_span = 31_557_600_000_000_000L let rec pp_si_span unit_str si_unit si_higher_unit ppf span = let geq x y = unsigned_compare x y >= 0 in let m = unsigned_div span si_unit in let n = unsigned_rem span si_unit in match m with let m_up = if Int64.equal n 0L then m else Int64.succ m in let span' = Int64.mul m_up si_unit in if geq span' si_higher_unit then uint64_ns_span ppf span' else pf ppf "%Ld%s" m_up unit_str One fractional digit w.o . trailing zero let f_factor = unsigned_div si_unit 10L in let f_m = unsigned_div n f_factor in let f_n = unsigned_rem n f_factor in let f_m_up = if Int64.equal f_n 0L then f_m else Int64.succ f_m in begin match f_m_up with | 0L -> pf ppf "%Ld%s" m unit_str | f when geq f 10L -> uint64_ns_span ppf Int64.(add (mul m si_unit) (mul f f_factor)) | f -> pf ppf "%Ld.%Ld%s" m f unit_str end Two or zero fractional digits w.o . trailing zero let f_factor = unsigned_div si_unit 100L in let f_m = unsigned_div n f_factor in let f_n = unsigned_rem n f_factor in let f_m_up = if Int64.equal f_n 0L then f_m else Int64.succ f_m in match f_m_up with | 0L -> pf ppf "%Ld%s" m unit_str | f when geq f 100L -> uint64_ns_span ppf Int64.(add (mul m si_unit) (mul f f_factor)) | f when Int64.equal (Int64.rem f 10L) 0L -> pf ppf "%Ld.%Ld%s" m (Int64.div f 10L) unit_str | f -> pf ppf "%Ld.%02Ld%s" m f unit_str and pp_non_si unit_str unit unit_lo_str unit_lo unit_lo_size ppf span = let geq x y = unsigned_compare x y >= 0 in let m = unsigned_div span unit in let n = unsigned_rem span unit in if Int64.equal n 0L then pf ppf "%Ld%s" m unit_str else let f_m = unsigned_div n unit_lo in let f_n = unsigned_rem n unit_lo in let f_m_up = if Int64.equal f_n 0L then f_m else Int64.succ f_m in match f_m_up with | f when geq f unit_lo_size -> uint64_ns_span ppf Int64.(add (mul m unit) (mul f unit_lo)) | f -> pf ppf "%Ld%s%Ld%s" m unit_str f unit_lo_str and uint64_ns_span ppf span = let geq x y = unsigned_compare x y >= 0 in let lt x y = unsigned_compare x y = -1 in match span with | s when lt s us_span -> pf ppf "%Ldns" s | s when lt s ms_span -> pp_si_span "us" us_span ms_span ppf s | s when lt s sec_span -> pp_si_span "ms" ms_span sec_span ppf s | s when lt s min_span -> pp_si_span "s" sec_span min_span ppf s | s when lt s hour_span -> pp_non_si "min" min_span "s" sec_span 60L ppf s | s when lt s day_span -> pp_non_si "h" hour_span "min" min_span 60L ppf s | s when lt s year_span -> pp_non_si "d" day_span "h" hour_span 24L ppf s | s -> let m = unsigned_div s year_span in let n = unsigned_rem s year_span in if Int64.equal n 0L then pf ppf "%Lda" m else let f_m = unsigned_div n day_span in let f_n = unsigned_rem n day_span in let f_m_up = if Int64.equal f_n 0L then f_m else Int64.succ f_m in match f_m_up with | f when geq f 366L -> pf ppf "%Lda" (Int64.succ m) | f -> pf ppf "%Lda%Ldd" m f type 'a vec = int * (int -> 'a) let iter_vec f (n, get) = for i = 0 to n - 1 do f i (get i) done let vec ?sep = iter_bindings ?sep iter_vec let on_string = using String.(fun s -> length s, get s) let on_bytes = using Bytes.(fun b -> length b, get b) let sub_vecs w (n, get) = (n - 1) / w + 1, fun j -> let off = w * j in min w (n - off), fun i -> get (i + off) let prefix0x = [ 0xf , fmt "%01x"; 0xff , fmt "%02x"; 0xfff , fmt "%03x"; 0xffff , fmt "%04x"; 0xfffff , fmt "%05x"; 0xffffff , fmt "%06x"; 0xfffffff , fmt "%07x"; ] let padded0x ~max = match List.find_opt (fun (x, _) -> max <= x) prefix0x with | Some (_, pp) -> pp | None -> fmt "%08x" let ascii ?(w = 0) ?(subst = const char '.') () ppf (n, _ as v) = let pp_char ppf (_, c) = if '\x20' <= c && c < '\x7f' then char ppf c else subst ppf () in vec pp_char ppf v; if n < w then sps (w - n) ppf () let octets ?(w = 0) ?(sep = sp) () ppf (n, _ as v) = let pp_sep ppf i = if i > 0 && i mod 2 = 0 then sep ppf () in let pp_char ppf (i, c) = pp_sep ppf i; pf ppf "%02x" (Char.code c) in vec ~sep:nop pp_char ppf v; for i = n to w - 1 do pp_sep ppf i; sps 2 ppf () done let addresses ?addr ?(w = 16) pp_vec ppf (n, _ as v) = let addr = match addr with | Some pp -> pp | _ -> padded0x ~max:(((n - 1) / w) * w) ++ const string ": " in let pp_sub ppf (i, sub) = addr ppf (i * w); box pp_vec ppf sub in vbox (vec pp_sub) ppf (sub_vecs w v) let hex ?(w = 16) () = addresses ~w ((octets ~w () |> box) ++ sps 2 ++ (ascii ~w () |> box)) let is_nl c = c = '\n' let is_nl_or_sp c = is_nl c || c = ' ' let is_white = function ' ' | '\t' .. '\r' -> true | _ -> false let not_white c = not (is_white c) let not_white_or_nl c = is_nl c || not_white c let rec stop_at sat ~start ~max s = if start > max then start else if sat s.[start] then start else stop_at sat ~start:(start + 1) ~max s let sub s start stop ~max = if start = stop then "" else if start = 0 && stop > max then s else String.sub s start (stop - start) let words ppf s = let max = String.length s - 1 in let rec loop start s = match stop_at is_white ~start ~max s with | stop when stop > max -> Format.pp_print_string ppf (sub s start stop ~max) | stop -> Format.pp_print_string ppf (sub s start stop ~max); match stop_at not_white ~start:stop ~max s with | stop when stop > max -> () | stop -> Format.pp_print_space ppf (); loop stop s in let start = stop_at not_white ~start:0 ~max s in if start > max then () else loop start s let paragraphs ppf s = let max = String.length s - 1 in let rec loop start s = match stop_at is_white ~start ~max s with | stop when stop > max -> Format.pp_print_string ppf (sub s start stop ~max) | stop -> Format.pp_print_string ppf (sub s start stop ~max); match stop_at not_white_or_nl ~start:stop ~max s with | stop when stop > max -> () | stop -> if s.[stop] <> '\n' then (Format.pp_print_space ppf (); loop stop s) else match stop_at not_white_or_nl ~start:(stop + 1) ~max s with | stop when stop > max -> () | stop -> if s.[stop] <> '\n' then (Format.pp_print_space ppf (); loop stop s) else match stop_at not_white ~start:(stop + 1) ~max s with | stop when stop > max -> () | stop -> Format.pp_force_newline ppf (); Format.pp_force_newline ppf (); loop stop s in let start = stop_at not_white ~start:0 ~max s in if start > max then () else loop start s let text ppf s = let max = String.length s - 1 in let rec loop start s = match stop_at is_nl_or_sp ~start ~max s with | stop when stop > max -> Format.pp_print_string ppf (sub s start stop ~max) | stop -> Format.pp_print_string ppf (sub s start stop ~max); begin match s.[stop] with | ' ' -> Format.pp_print_space ppf () | '\n' -> Format.pp_force_newline ppf () | _ -> assert false end; loop (stop + 1) s in loop 0 s let lines ppf s = let max = String.length s - 1 in let rec loop start s = match stop_at is_nl ~start ~max s with | stop when stop > max -> Format.pp_print_string ppf (sub s start stop ~max) | stop -> Format.pp_print_string ppf (sub s start stop ~max); Format.pp_force_newline ppf (); loop (stop + 1) s in loop 0 s let truncated ~max ppf s = match String.length s <= max with | true -> Format.pp_print_string ppf s | false -> for i = 0 to max - 4 do Format.pp_print_char ppf s.[i] done; Format.pp_print_string ppf "..." let text_loc ppf ((l0, c0), (l1, c1)) = if (l0 : int) == (l1 : int) && (c0 : int) == (c1 : int) then pf ppf "%d.%d" l0 c0 else pf ppf "%d.%d-%d.%d" l0 c0 l1 c1 HCI fragments let one_of ?(empty = nop) pp_v ppf = function | [] -> empty ppf () | [v] -> pp_v ppf v | [v0; v1] -> pf ppf "@[either %a or@ %a@]" pp_v v0 pp_v v1 | _ :: _ as vs -> let rec loop ppf = function | [v] -> pf ppf "or@ %a" pp_v v | v :: vs -> pf ppf "%a,@ " pp_v v; loop ppf vs | [] -> assert false in pf ppf "@[one@ of@ %a@]" loop vs let did_you_mean ?(pre = any "Unknown") ?(post = nop) ~kind pp_v ppf (v, hints) = match hints with | [] -> pf ppf "@[%a %s %a%a.@]" pre () kind pp_v v post () | hints -> pf ppf "@[%a %s %a%a.@ Did you mean %a ?@]" pre () kind pp_v v post () (one_of pp_v) hints module Imap = Map.Make (Int) type 'a attr = int * ('a -> string) * (string -> 'a) let id = ref 0 let attr (type a) enc dec = incr id; (!id, enc, dec) type Format.stag += | Fmt_store_get : 'a attr -> Format.stag | Fmt_store_set : 'a attr * 'a -> Format.stag let store () = let s = ref Imap.empty in fun ~other -> function | Fmt_store_get (id, _, _) -> Option.value ~default:"" (Imap.find_opt id !s) | Fmt_store_set ((id, enc, _), v) -> s := Imap.add id (enc v) !s; "ok" | stag -> other stag let setup_store ppf = let funs = Format.pp_get_formatter_stag_functions ppf () in let mark_open_stag = store () ~other:funs.mark_open_stag in Format.pp_set_formatter_stag_functions ppf { funs with mark_open_stag } let store_op op ppf = let funs = Format.pp_get_formatter_stag_functions ppf () in funs.mark_open_stag op let get (_, _, dec as attr) ppf = match store_op (Fmt_store_get attr) ppf with | "" -> None | s -> Some (dec s) let rec set attr v ppf = match store_op (Fmt_store_set (attr, v)) ppf with | "ok" -> () | _ -> setup_store ppf; set attr v ppf let def x = function Some y -> y | _ -> x let utf_8_attr = let enc = function true -> "t" | false -> "f" in let dec = function "t" -> true | "f" -> false | _ -> assert false in attr enc dec let utf_8 ppf = get utf_8_attr ppf |> def true let set_utf_8 ppf x = set utf_8_attr x ppf type style_renderer = [ `Ansi_tty | `None ] let style_renderer_attr = let enc = function `Ansi_tty -> "A" | `None -> "N" in let dec = function "A" -> `Ansi_tty | "N" -> `None | _ -> assert false in attr enc dec let style_renderer ppf = get style_renderer_attr ppf |> def `None let set_style_renderer ppf x = set style_renderer_attr x ppf let with_buffer ?like buf = let ppf = Format.formatter_of_buffer buf in N.B. this does slighty more it also makes buf use other installed semantic tag actions . semantic tag actions. *) match like with | None -> ppf | Some like -> let funs = Format.pp_get_formatter_stag_functions like () in Format.pp_set_formatter_stag_functions ppf funs; ppf let str_like ppf fmt = let buf = Buffer.create 64 in let bppf = with_buffer ~like:ppf buf in let flush ppf = Format.pp_print_flush ppf (); let s = Buffer.contents buf in Buffer.reset buf; s in Format.kfprintf flush bppf fmt let if_utf_8 pp_u pp = fun ppf v -> (if utf_8 ppf then pp_u else pp) ppf v type color = [ `Black | `Blue | `Cyan | `Green | `Magenta | `Red | `White | `Yellow ] type style = [ `None | `Bold | `Faint | `Italic | `Underline | `Reverse | `Fg of [ color | `Hi of color ] | `Bg of [ color | `Hi of color ] let ansi_style_code = function | `Bold -> "1" | `Faint -> "2" | `Italic -> "3" | `Underline -> "4" | `Reverse -> "7" | `Fg `Black -> "30" | `Fg `Red -> "31" | `Fg `Green -> "32" | `Fg `Yellow -> "33" | `Fg `Blue -> "34" | `Fg `Magenta -> "35" | `Fg `Cyan -> "36" | `Fg `White -> "37" | `Bg `Black -> "40" | `Bg `Red -> "41" | `Bg `Green -> "42" | `Bg `Yellow -> "43" | `Bg `Blue -> "44" | `Bg `Magenta -> "45" | `Bg `Cyan -> "46" | `Bg `White -> "47" | `Fg (`Hi `Black) -> "90" | `Fg (`Hi `Red) -> "91" | `Fg (`Hi `Green) -> "92" | `Fg (`Hi `Yellow) -> "93" | `Fg (`Hi `Blue) -> "94" | `Fg (`Hi `Magenta) -> "95" | `Fg (`Hi `Cyan) -> "96" | `Fg (`Hi `White) -> "97" | `Bg (`Hi `Black) -> "100" | `Bg (`Hi `Red) -> "101" | `Bg (`Hi `Green) -> "102" | `Bg (`Hi `Yellow) -> "103" | `Bg (`Hi `Blue) -> "104" | `Bg (`Hi `Magenta) -> "105" | `Bg (`Hi `Cyan) -> "106" | `Bg (`Hi `White) -> "107" | `None -> "0" | `Black -> "30" | `Red -> "31" | `Green -> "32" | `Yellow -> "33" | `Blue -> "34" | `Magenta -> "35" | `Cyan -> "36" | `White -> "37" let pp_sgr ppf style = Format.pp_print_as ppf 0 "\027["; Format.pp_print_as ppf 0 style; Format.pp_print_as ppf 0 "m" let curr_style = attr Fun.id Fun.id let styled style pp_v ppf v = match style_renderer ppf with | `None -> pp_v ppf v | `Ansi_tty -> let prev = match get curr_style ppf with | None -> let zero = "0" in set curr_style zero ppf; zero | Some s -> s in let here = ansi_style_code style in let curr = match style with | `None -> here | _ -> String.concat ";" [prev; here] in let finally () = set curr_style prev ppf in set curr_style curr ppf; Fun.protect ~finally @@ fun () -> pp_sgr ppf here; pp_v ppf v; pp_sgr ppf prev Records let id = Fun.id let label = styled (`Fg `Yellow) string let field ?(label = label) ?(sep = any ":@ ") l prj pp_v ppf v = pf ppf "@[<1>%a%a%a@]" label l sep () pp_v (prj v) let record ?(sep = cut) pps = vbox (concat ~sep pps) let of_to_string f ppf v = string ppf (f v) let to_to_string pp_v v = str "%a" pp_v v let strf = str let kstrf = kstr let strf_like = str_like let always = any let unit = any let prefix pp_p pp_v ppf v = pp_p ppf (); pp_v ppf v let suffix pp_s pp_v ppf v = pp_v ppf v; pp_s ppf () let styled_unit style fmt = styled style (any fmt) --------------------------------------------------------------------------- Copyright ( c ) 2014 The fmt programmers Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2014 The fmt programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
392c38949e606b3fe3a57797d1774e599cefd8c154831a997a17272ac4719e4b
qfpl/reflex-workshop
Apply.hs
| Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation License : : Stability : experimental Portability : non - portable Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GADTs #-} module Workshop.Behaviors.Instances.Apply ( exApply ) where import qualified Data.Text as Text import Reflex.Dom.Core import Types.Exercise import Exercises.Behaviors.Instances.Apply import Solutions.Behaviors.Instances.Apply mkIn :: MonadWidget t m => m (Dynamic t Int, Dynamic t Int) mkIn = do eTick <- tickLossyFromPostBuildTime 1 d <- count eTick let mkD n = (`div` n) <$> d d1 = mkD 2 d2 = mkD 3 let eIn1 = current d1 <@ updated d eIn2 = current d2 <@ updated d collect = holdDyn "" . fmap (Text.pack .show) divClass "row" $ do divClass "col-6" $ text "Behavior in 1" divClass "col-6" $ do dIn <- collect eIn1 dynText dIn divClass "row" $ do divClass "col-6" $ text "Behavior in 2" divClass "col-6" $ do dIn <- collect eIn2 dynText dIn pure (d1, d2) mk :: MonadWidget t m => (Behavior t Int -> Behavior t Int -> Behavior t Int) -> (Dynamic t Int, Dynamic t Int) -> m () mk fn (d1, d2) = do let eOut = fn (current d1) (current d2) <@ leftmost [updated d1, updated d2] dOut <- holdDyn "" . fmap (Text.pack . show) $ eOut divClass "row" $ do divClass "col-6" $ text "Behavior out" divClass "col-6" $ do dynText dOut exApply :: MonadWidget t m => Exercise m exApply = let problem = Problem "pages/behaviors/instances/apply.html" "src/Exercises/Behaviors/Instances/Apply.hs" mempty progress = ProgressSetup True mkIn (mk applySolution) (mk applyExercise) solution = Solution [ "pages/behaviors/instances/apply/solution/0.html" , "pages/behaviors/instances/apply/solution/1.html" , "pages/behaviors/instances/apply/solution/2.html" , "pages/behaviors/instances/apply/solution/3.html" ] in Exercise "apply" "apply" problem progress solution
null
https://raw.githubusercontent.com/qfpl/reflex-workshop/244ef13fb4b2e884f455eccc50072e98d1668c9e/src/Workshop/Behaviors/Instances/Apply.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE GADTs #
| Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation License : : Stability : experimental Portability : non - portable Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} module Workshop.Behaviors.Instances.Apply ( exApply ) where import qualified Data.Text as Text import Reflex.Dom.Core import Types.Exercise import Exercises.Behaviors.Instances.Apply import Solutions.Behaviors.Instances.Apply mkIn :: MonadWidget t m => m (Dynamic t Int, Dynamic t Int) mkIn = do eTick <- tickLossyFromPostBuildTime 1 d <- count eTick let mkD n = (`div` n) <$> d d1 = mkD 2 d2 = mkD 3 let eIn1 = current d1 <@ updated d eIn2 = current d2 <@ updated d collect = holdDyn "" . fmap (Text.pack .show) divClass "row" $ do divClass "col-6" $ text "Behavior in 1" divClass "col-6" $ do dIn <- collect eIn1 dynText dIn divClass "row" $ do divClass "col-6" $ text "Behavior in 2" divClass "col-6" $ do dIn <- collect eIn2 dynText dIn pure (d1, d2) mk :: MonadWidget t m => (Behavior t Int -> Behavior t Int -> Behavior t Int) -> (Dynamic t Int, Dynamic t Int) -> m () mk fn (d1, d2) = do let eOut = fn (current d1) (current d2) <@ leftmost [updated d1, updated d2] dOut <- holdDyn "" . fmap (Text.pack . show) $ eOut divClass "row" $ do divClass "col-6" $ text "Behavior out" divClass "col-6" $ do dynText dOut exApply :: MonadWidget t m => Exercise m exApply = let problem = Problem "pages/behaviors/instances/apply.html" "src/Exercises/Behaviors/Instances/Apply.hs" mempty progress = ProgressSetup True mkIn (mk applySolution) (mk applyExercise) solution = Solution [ "pages/behaviors/instances/apply/solution/0.html" , "pages/behaviors/instances/apply/solution/1.html" , "pages/behaviors/instances/apply/solution/2.html" , "pages/behaviors/instances/apply/solution/3.html" ] in Exercise "apply" "apply" problem progress solution
813c8f40d6ffa578da3bdbeee9453a9c1a2dcadbca322c59d46dc79cf289d803
skanev/playground
23.scm
EOPL exercise 3.23 ; ; What is the value of the following PROC program? ; let = proc ( maker ) ; proc (x) if ) ; then 0 else -(((maker maker ) -(x , 1 ) ) , -4 ) in let times4 = proc ( x ) ( ( makemult ) x ) in ( times4 3 ) ; ; Use tricks of this program to write a procedure for factorial in PROC. As a hint , remember that you can use currying ( exercise 3.20 ) to define a two - argument procedure times . This smells of the Y combinator . Cool . The program returns 12 , as the names ; of its procedures suggest. (load-relative "cases/proc/all.scm") (define the-given-program "let makemult = proc (maker) proc (x) if zero?(x) then 0 else -(((maker maker) -(x, 1)), -(0, 4)) in let times4 = proc (x) ((makemult makemult) x) in (times4 3)") (define factorial-5-program "let makemult = proc (maker) proc (x) proc (y) if zero?(y) then 0 else -((((maker maker) x) -(y, 1)), -(0, x)) in let times = proc (x) proc (y) (((makemult makemult) x) y) in let makefact = proc (fact) proc (n) if zero?(n) then 1 else ((times n) ((fact fact) -(n, 1))) in let factorial = proc (n) ((makefact makefact) n) in (factorial 5)")
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/eopl/03/23.scm
scheme
What is the value of the following PROC program? proc (x) then 0 Use tricks of this program to write a procedure for factorial in PROC. As a of its procedures suggest.
EOPL exercise 3.23 let = proc ( maker ) if ) else -(((maker maker ) -(x , 1 ) ) , -4 ) in let times4 = proc ( x ) ( ( makemult ) x ) in ( times4 3 ) hint , remember that you can use currying ( exercise 3.20 ) to define a two - argument procedure times . This smells of the Y combinator . Cool . The program returns 12 , as the names (load-relative "cases/proc/all.scm") (define the-given-program "let makemult = proc (maker) proc (x) if zero?(x) then 0 else -(((maker maker) -(x, 1)), -(0, 4)) in let times4 = proc (x) ((makemult makemult) x) in (times4 3)") (define factorial-5-program "let makemult = proc (maker) proc (x) proc (y) if zero?(y) then 0 else -((((maker maker) x) -(y, 1)), -(0, x)) in let times = proc (x) proc (y) (((makemult makemult) x) y) in let makefact = proc (fact) proc (n) if zero?(n) then 1 else ((times n) ((fact fact) -(n, 1))) in let factorial = proc (n) ((makefact makefact) n) in (factorial 5)")
5893861df5a84eff7efb038576df0421d47fedc043a767d837c2f63d44b9d2b1
picty/parsifal
struct-0d.ml
struct s = { x : uint8; parse_field y : copy(x+1); }
null
https://raw.githubusercontent.com/picty/parsifal/767a1d558ea6da23ada46d8d96a057514b0aa2a8/syntax/unit/struct-0d.ml
ocaml
struct s = { x : uint8; parse_field y : copy(x+1); }
943e695a562764e02f95af6f5435dbe3cb7b18115249f954ec91dcb82887bd60
MastodonC/kixi.hecuba
calculated_fields.clj
(ns kixi.hecuba.data.calculated-fields "Calcualated fields." (:require [kixi.hecuba.storage.db :as db] [qbits.hayt :as hayt] [clojure.tools.logging :as log] [clojure.string :as string] [clj-time.core :as t] [clj-time.coerce :as tc] [kixi.hecuba.data.measurements :as measurements] [kixi.hecuba.data.calculate :as calculate])) (defmulti calculate-field (fn [store device_id type period measurements operation] operation)) (defmethod calculate-field :actual-annual [store device_id type period measurements _] (let [calculate-fn (fn [measurements] (case period "INSTANT" (calculate/average-reading measurements) "PULSE" (reduce + measurements)))] (calculate-fn measurements))) (defn escape [string] (string/escape string {\space "__SPACE__" \& "__AMPERSAND__" \/ "__SLASH__"} )) (defn calculate [store sensor operation calculation-name range] (let [{:keys [device_id type period]} sensor] (log/info "Calculating field: " operation "for sensor: " (str device_id "-" type) "and range: " range) (db/with-session [session (:hecuba-session store)] (let [measurements (measurements/parse-measurements (measurements/measurements-for-range store sensor range (t/hours 1))) filtered (filter number? (map :value measurements)) {:keys [entity_id name]} (first (db/execute session (hayt/select :devices (hayt/where [[= :id device_id]])))) value (calculate-field store device_id type period filtered operation) timestamp (tc/to-date (t/now)) field (str calculation-name ":" device_id ":" (escape type))] (db/execute session (hayt/update :entities (hayt/set-columns {:calculated_fields_values [+ {field (str value)}] :calculated_fields_labels [+ {field (str name type)}] :calculated_fields_last_calc [+ {field timestamp}]}) (hayt/where [[= :id entity_id]]))))) (log/info "Finished calculating field: " operation "for sensor: " (str device_id "-" type) "and range: " range)))
null
https://raw.githubusercontent.com/MastodonC/kixi.hecuba/467400bbe670e74420a2711f7d49e869ab2b3e21/src/clj/kixi/hecuba/data/calculated_fields.clj
clojure
(ns kixi.hecuba.data.calculated-fields "Calcualated fields." (:require [kixi.hecuba.storage.db :as db] [qbits.hayt :as hayt] [clojure.tools.logging :as log] [clojure.string :as string] [clj-time.core :as t] [clj-time.coerce :as tc] [kixi.hecuba.data.measurements :as measurements] [kixi.hecuba.data.calculate :as calculate])) (defmulti calculate-field (fn [store device_id type period measurements operation] operation)) (defmethod calculate-field :actual-annual [store device_id type period measurements _] (let [calculate-fn (fn [measurements] (case period "INSTANT" (calculate/average-reading measurements) "PULSE" (reduce + measurements)))] (calculate-fn measurements))) (defn escape [string] (string/escape string {\space "__SPACE__" \& "__AMPERSAND__" \/ "__SLASH__"} )) (defn calculate [store sensor operation calculation-name range] (let [{:keys [device_id type period]} sensor] (log/info "Calculating field: " operation "for sensor: " (str device_id "-" type) "and range: " range) (db/with-session [session (:hecuba-session store)] (let [measurements (measurements/parse-measurements (measurements/measurements-for-range store sensor range (t/hours 1))) filtered (filter number? (map :value measurements)) {:keys [entity_id name]} (first (db/execute session (hayt/select :devices (hayt/where [[= :id device_id]])))) value (calculate-field store device_id type period filtered operation) timestamp (tc/to-date (t/now)) field (str calculation-name ":" device_id ":" (escape type))] (db/execute session (hayt/update :entities (hayt/set-columns {:calculated_fields_values [+ {field (str value)}] :calculated_fields_labels [+ {field (str name type)}] :calculated_fields_last_calc [+ {field timestamp}]}) (hayt/where [[= :id entity_id]]))))) (log/info "Finished calculating field: " operation "for sensor: " (str device_id "-" type) "and range: " range)))
cac0edf99399f4d2ec30a29d3dee8baca20c1e1fa5ee85d50f4a6d47e79af9b1
GaloisInc/pate
SimulatorHooks.hs
# LANGUAGE DataKinds # {-# LANGUAGE GADTs #-} # LANGUAGE ImplicitParams # {-# LANGUAGE RankNTypes #-} # LANGUAGE TupleSections # # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # # LANGUAGE ViewPatterns # -- | Modified crucible extension evaluators for the InlineCallee symbolic execution -- -- The goal of these overrides is to concretize as much as we can eagerly to -- improve the performance of the memory model during symbolic execution. Many -- code constructs lead to symbolic writes, which cause the memory model to -- grind to a halt quickly. However, the vast majority of them are really concrete ( if you ask the SMT solver for a model , there will only be one ) . We -- take advantage of this by concretizing addresses during writes. -- -- This module will also support any other optimizations we want. It could, for -- example, add hooks over operations to reduce the number of safety checks -- (which are not very relevant for the pate verifier). module Pate.Verification.SimulatorHooks ( hookedMacawExtensions ) where import Control.Lens ( (^.), (&), (%~) ) import qualified Data.Parameterized.Classes as PC import qualified Data.Parameterized.NatRepr as PN import qualified Data.Traversable as T import qualified Data.Vector as V import GHC.Stack ( HasCallStack ) import qualified What4.BaseTypes as WT import qualified What4.Expr as WE import qualified What4.Interface as WI import qualified What4.Protocol.Online as WPO import qualified What4.Symbol as WS import qualified Data.Macaw.CFG as DMC import qualified Data.Macaw.Symbolic as DMS import qualified Data.Macaw.Symbolic.Backend as DMSB import qualified Lang.Crucible.Backend as LCB import qualified Lang.Crucible.Backend.Online as LCBO import qualified Lang.Crucible.CFG.Extension as LCCE import qualified Lang.Crucible.LLVM.Bytes as LCLB import qualified Lang.Crucible.LLVM.DataLayout as LCLD import qualified Lang.Crucible.LLVM.MemModel as LCLM import qualified Lang.Crucible.Simulator as LCS import qualified Lang.Crucible.Simulator.ExecutionTree as LCSE import qualified Lang.Crucible.Simulator.GlobalState as LCSG import qualified Lang.Crucible.Simulator.Intrinsics as LCSI import qualified Lang.Crucible.Types as LCT import qualified Pate.Panic as PP import qualified Pate.Verification.Concretize as PVC getMem :: (HasCallStack) => LCS.CrucibleState s sym ext rtp blocks r ctx -> LCS.GlobalVar (LCT.IntrinsicType nm args) -> IO (LCSI.Intrinsic sym nm args) getMem st mvar = case LCSG.lookupGlobal mvar (st ^. LCSE.stateTree . LCSE.actFrame . LCS.gpGlobals) of Just mem -> return mem Nothing -> PP.panic PP.InlineCallee "getMem" ["Global heap value not initialized: " ++ show mvar] setMem :: LCS.CrucibleState s sym ext rtp blocks r ctx -> LCS.GlobalVar (LCT.IntrinsicType nm args) -> LCSI.Intrinsic sym nm args -> LCS.CrucibleState s sym ext rtp blocks r ctx setMem st mvar mem = st & LCSE.stateTree . LCSE.actFrame . LCS.gpGlobals %~ LCSG.insertGlobal mvar mem memReprToStorageType :: (HasCallStack) => DMC.MemRepr ty -> IO LCLM.StorageType memReprToStorageType memRep = case memRep of DMC.BVMemRepr bytes _endian -> do return $ LCLM.bitvectorType (LCLB.Bytes (PN.intValue bytes)) DMC.FloatMemRepr floatRep _endian -> do case floatRep of DMC.SingleFloatRepr -> return LCLM.floatType DMC.DoubleFloatRepr -> return LCLM.doubleType DMC.X86_80FloatRepr -> return LCLM.x86_fp80Type _ -> PP.panic PP.InlineCallee "memReprToStorageType" [ "Do not support memory accesses to " ++ show floatRep ++ " values"] DMC.PackedVecMemRepr n eltType -> do eltStorageType <- memReprToStorageType eltType return $ LCLM.arrayType (PN.natValue n) eltStorageType resolveMemVal :: (HasCallStack) => DMC.MemRepr ty -> LCLM.StorageType -> LCS.RegValue sym (DMS.ToCrucibleType ty) -> LCLM.LLVMVal sym resolveMemVal (DMC.BVMemRepr bytes _endian) _ (LCLM.LLVMPointer base bits) = case PN.leqMulPos (PN.knownNat @8) bytes of PN.LeqProof -> LCLM.LLVMValInt base bits resolveMemVal (DMC.FloatMemRepr floatRep _endian) _ val = case floatRep of DMC.SingleFloatRepr -> LCLM.LLVMValFloat LCLM.SingleSize val DMC.DoubleFloatRepr -> LCLM.LLVMValFloat LCLM.DoubleSize val DMC.X86_80FloatRepr -> LCLM.LLVMValFloat LCLM.X86_FP80Size val _ -> PP.panic PP.InlineCallee "resolveMemVal" ["Do not support memory accesses to " ++ show floatRep ++ " values"] resolveMemVal (DMC.PackedVecMemRepr n eltType) stp val = case LCLM.storageTypeF stp of LCLM.Array cnt eltStp | cnt == PN.natValue n, fromIntegral (V.length val) == PN.natValue n -> LCLM.LLVMValArray eltStp (resolveMemVal eltType eltStp <$> val) _ -> PP.panic PP.InlineCallee "resolveMemVal" ["Unexpected storage type for packed vec"] memValToCrucible :: ( LCB.IsSymInterface sym ) => DMC.MemRepr ty -> LCLM.LLVMVal sym -> Either String (LCS.RegValue sym (DMS.ToCrucibleType ty)) memValToCrucible memRep val = case memRep of -- Convert memory model value to pointer DMC.BVMemRepr bytes _endian -> do let bitw = PN.natMultiply (PN.knownNat @8) bytes case val of LCLM.LLVMValInt base off | Just PC.Refl <- PC.testEquality (WI.bvWidth off) bitw -> pure (LCLM.LLVMPointer base off) _ -> unexpectedMemVal DMC.FloatMemRepr floatRep _endian -> case val of LCLM.LLVMValFloat sz fltVal -> case (floatRep, sz) of (DMC.SingleFloatRepr, LCLM.SingleSize) -> pure fltVal (DMC.DoubleFloatRepr, LCLM.DoubleSize) -> pure fltVal (DMC.X86_80FloatRepr, LCLM.X86_FP80Size) -> pure fltVal _ -> unexpectedMemVal _ -> unexpectedMemVal DMC.PackedVecMemRepr _expectedLen eltMemRepr -> do case val of LCLM.LLVMValArray _ v -> do T.traverse (memValToCrucible eltMemRepr) v _ -> unexpectedMemVal where unexpectedMemVal = Left "Unexpected value read from memory" tryGlobPtr :: (LCB.IsSymBackend sym bak) => bak -> LCS.RegValue sym LCLM.Mem -> DMS.GlobalMap sym LCLM.Mem w -> LCLM.LLVMPtr sym w -> IO (LCLM.LLVMPtr sym w) tryGlobPtr bak mem mapBVAddress val@(LCLM.LLVMPointer base offset) | Just blockId <- WI.asNat base , blockId /= 0 = do If we know that the blockId is concretely not zero , the pointer is already translated into an LLVM pointer and can be passed through . return val | otherwise = do If the blockId is zero , we have to translate it into a proper LLVM -- pointer -- -- Otherwise, the blockId is symbolic and we need to create a mux that -- conditionally performs the translation. DMS.applyGlobalMap mapBVAddress bak mem base offset concretizingWrite :: ( LCB.IsSymInterface sym , sym ~ WE.ExprBuilder scope st fs , WPO.OnlineSolver solver , LCLM.HasPtrWidth ptrW , LCLM.HasLLVMAnn sym , ptrW ~ DMC.ArchAddrWidth arch , HasCallStack ) => LCS.GlobalVar LCLM.Mem -> DMS.GlobalMap sym LCLM.Mem ptrW -> LCBO.OnlineBackend solver scope st fs -> LCS.CrucibleState p sym (DMS.MacawExt arch) rtp blocks r ctx -> DMC.AddrWidthRepr ptrW -> DMC.MemRepr ty -> LCS.RegEntry sym (LCLM.LLVMPointerType ptrW) -> LCS.RegEntry sym (DMS.ToCrucibleType ty) -> IO ((), LCS.CrucibleState p sym (DMS.MacawExt arch) rtp blocks r ctx) concretizingWrite memVar globs bak crucState _addrWidth memRep (LCS.regValue -> ptr) (LCS.regValue -> value) = do mem <- getMem crucState memVar -- Attempt to concretize the pointer we are writing to, so that we can minimize symbolic writes ptr' <- tryGlobPtr bak mem globs ptr ptr'' <- PVC.resolveSingletonPointer (PVC.wrappedBackend bak) ptr' ty <- memReprToStorageType memRep let memVal = resolveMemVal memRep ty value mem' <- LCLM.storeRaw bak mem ptr'' ty LCLD.noAlignment memVal return ((), setMem crucState memVar mem') concretizingRead :: ( LCB.IsSymInterface sym , sym ~ WE.ExprBuilder scope st fs , WPO.OnlineSolver solver , LCLM.HasPtrWidth ptrW , ptrW ~ DMC.ArchAddrWidth arch , LCLM.HasLLVMAnn sym , ?memOpts :: LCLM.MemOptions , HasCallStack ) => LCS.GlobalVar LCLM.Mem -> DMS.GlobalMap sym LCLM.Mem ptrW -> LCBO.OnlineBackend solver scope st fs -> LCS.CrucibleState p sym (DMS.MacawExt arch) rtp blocks r ctx -> DMC.AddrWidthRepr ptrW -> DMC.MemRepr ty -> LCS.RegEntry sym (LCLM.LLVMPointerType ptrW) -> IO (LCS.RegValue sym (DMS.ToCrucibleType ty)) concretizingRead memVar globs bak crucState _addrWidth memRep (LCS.regValue -> ptr) = do let sym = LCB.backendGetSym bak mem <- getMem crucState memVar -- Attempt to concretize the pointer we are reading from, avoiding a symbolic -- read if possible ptr' <- tryGlobPtr bak mem globs ptr ptr''@(LCLM.LLVMPointer _ off) <- PVC.resolveSingletonPointer (PVC.wrappedBackend bak) ptr' case WI.asBV off of Just _ -> do ty <- memReprToStorageType memRep res <- LCLM.assertSafe bak =<< LCLM.loadRaw sym mem ptr'' ty LCLD.noAlignment case memValToCrucible memRep res of Left err -> PP.panic PP.InlineCallee "concretizingRead" [err] Right crucVal -> return crucVal Nothing -> do -- As an experiment, consider: what happens if we just return arbitrary -- symbolic values for symbolic reads? We know that the verifier will -- never return if we actually try one. case memRep of DMC.BVMemRepr nBytesRepr _endianness -> do let bitw = PN.natMultiply (PN.knownNat @8) nBytesRepr case PC.testEquality (WI.bvWidth off) bitw of Just PC.Refl -> do symOff <- WI.freshConstant sym (WS.safeSymbol "symbolicReadBytes") (WT.BaseBVRepr bitw) LCLM.llvmPointer_bv sym symOff _ -> PP.panic PP.InlineCallee "concretizingRead" ["Unsupported memRepr: " ++ show memRep] _ -> PP.panic PP.InlineCallee "concretizingRead" ["Unsupported memRepr: " ++ show memRep] statementWrapper :: ( LCB.IsSymInterface sym , sym ~ WE.ExprBuilder scope st fs , WPO.OnlineSolver solver , LCLM.HasPtrWidth (DMC.ArchAddrWidth arch) , LCLM.HasLLVMAnn sym , ?memOpts :: LCLM.MemOptions , HasCallStack ) => LCS.GlobalVar LCLM.Mem -> DMS.GlobalMap sym LCLM.Mem (DMC.ArchAddrWidth arch) -> LCBO.OnlineBackend solver scope st fs -> LCS.ExtensionImpl p sym (DMS.MacawExt arch) -> DMSB.MacawEvalStmtFunc (LCCE.StmtExtension (DMS.MacawExt arch)) p sym (DMS.MacawExt arch) statementWrapper mvar globs bak baseExt stmt crucState = let sym = LCB.backendGetSym bak in case stmt of DMS.MacawWriteMem addrWidth memRep ptr value -> concretizingWrite mvar globs bak crucState addrWidth memRep ptr value DMS.MacawReadMem addrWidth memRep ptr -> (, crucState) <$> concretizingRead mvar globs bak crucState addrWidth memRep ptr DMS.PtrMux _w (LCS.regValue -> c) (LCS.regValue -> x) (LCS.regValue -> y) -> do -- The macaw-symbolic version of this operator adds a number of safety -- checks to try to decide early if the input pointers are valid. This -- version is lazier and just constructs the pointer. -- -- The macaw-symbolic defensive checks add an "undefined" pointer into the -- mux as a fallthrough case, which turns into a symbolic read if used as -- a memory address. ptr <- LCLM.muxLLVMPtr sym c x y return (ptr, crucState) _ -> LCS.extensionExec baseExt stmt crucState | Macaw extensions for Crucible that have some optimizations required for the -- pate verifier to scale hookedMacawExtensions :: ( LCB.IsSymInterface sym , sym ~ WE.ExprBuilder scope st fs , WPO.OnlineSolver solver , LCLM.HasLLVMAnn sym , LCLM.HasPtrWidth (DMC.ArchAddrWidth arch) , ?memOpts :: LCLM.MemOptions ) => LCBO.OnlineBackend solver scope st fs -- ^ The (online) symbolic backend -> DMS.MacawArchEvalFn p sym LCLM.Mem arch -- ^ A set of interpretations for architecture-specific functions -> LCS.GlobalVar LCLM.Mem -- ^ The Crucible global variable containing the current state of the memory -- model -> DMS.GlobalMap sym LCLM.Mem (DMC.ArchAddrWidth arch) -- ^ A function that maps bitvectors to valid memory model pointers -> DMS.LookupFunctionHandle p sym arch -- ^ A function to translate virtual addresses into function handles -- dynamically during symbolic execution -> DMS.LookupSyscallHandle p sym arch -- ^ A function to examine the machine state to determine which system call -- should be invoked; returns the function handle to invoke -> DMS.MkGlobalPointerValidityAssertion sym (DMC.ArchAddrWidth arch) -- ^ A function to make memory validity predicates (see 'MkGlobalPointerValidityAssertion' for details) -> LCS.ExtensionImpl p sym (DMS.MacawExt arch) hookedMacawExtensions bak f mvar globs lookupH lookupSyscall toMemPred = baseExtension { LCS.extensionExec = statementWrapper mvar globs bak baseExtension } where baseExtension = DMS.macawExtensions f mvar globs lookupH lookupSyscall toMemPred
null
https://raw.githubusercontent.com/GaloisInc/pate/daa961af333c1e5a62391a45e679cbdae9798ed5/src/Pate/Verification/SimulatorHooks.hs
haskell
# LANGUAGE GADTs # # LANGUAGE RankNTypes # | Modified crucible extension evaluators for the InlineCallee symbolic execution The goal of these overrides is to concretize as much as we can eagerly to improve the performance of the memory model during symbolic execution. Many code constructs lead to symbolic writes, which cause the memory model to grind to a halt quickly. However, the vast majority of them are really take advantage of this by concretizing addresses during writes. This module will also support any other optimizations we want. It could, for example, add hooks over operations to reduce the number of safety checks (which are not very relevant for the pate verifier). Convert memory model value to pointer pointer Otherwise, the blockId is symbolic and we need to create a mux that conditionally performs the translation. Attempt to concretize the pointer we are writing to, so that we can minimize symbolic writes Attempt to concretize the pointer we are reading from, avoiding a symbolic read if possible As an experiment, consider: what happens if we just return arbitrary symbolic values for symbolic reads? We know that the verifier will never return if we actually try one. The macaw-symbolic version of this operator adds a number of safety checks to try to decide early if the input pointers are valid. This version is lazier and just constructs the pointer. The macaw-symbolic defensive checks add an "undefined" pointer into the mux as a fallthrough case, which turns into a symbolic read if used as a memory address. pate verifier to scale ^ The (online) symbolic backend ^ A set of interpretations for architecture-specific functions ^ The Crucible global variable containing the current state of the memory model ^ A function that maps bitvectors to valid memory model pointers ^ A function to translate virtual addresses into function handles dynamically during symbolic execution ^ A function to examine the machine state to determine which system call should be invoked; returns the function handle to invoke ^ A function to make memory validity predicates (see 'MkGlobalPointerValidityAssertion' for details)
# LANGUAGE DataKinds # # LANGUAGE ImplicitParams # # LANGUAGE TupleSections # # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # # LANGUAGE ViewPatterns # concrete ( if you ask the SMT solver for a model , there will only be one ) . We module Pate.Verification.SimulatorHooks ( hookedMacawExtensions ) where import Control.Lens ( (^.), (&), (%~) ) import qualified Data.Parameterized.Classes as PC import qualified Data.Parameterized.NatRepr as PN import qualified Data.Traversable as T import qualified Data.Vector as V import GHC.Stack ( HasCallStack ) import qualified What4.BaseTypes as WT import qualified What4.Expr as WE import qualified What4.Interface as WI import qualified What4.Protocol.Online as WPO import qualified What4.Symbol as WS import qualified Data.Macaw.CFG as DMC import qualified Data.Macaw.Symbolic as DMS import qualified Data.Macaw.Symbolic.Backend as DMSB import qualified Lang.Crucible.Backend as LCB import qualified Lang.Crucible.Backend.Online as LCBO import qualified Lang.Crucible.CFG.Extension as LCCE import qualified Lang.Crucible.LLVM.Bytes as LCLB import qualified Lang.Crucible.LLVM.DataLayout as LCLD import qualified Lang.Crucible.LLVM.MemModel as LCLM import qualified Lang.Crucible.Simulator as LCS import qualified Lang.Crucible.Simulator.ExecutionTree as LCSE import qualified Lang.Crucible.Simulator.GlobalState as LCSG import qualified Lang.Crucible.Simulator.Intrinsics as LCSI import qualified Lang.Crucible.Types as LCT import qualified Pate.Panic as PP import qualified Pate.Verification.Concretize as PVC getMem :: (HasCallStack) => LCS.CrucibleState s sym ext rtp blocks r ctx -> LCS.GlobalVar (LCT.IntrinsicType nm args) -> IO (LCSI.Intrinsic sym nm args) getMem st mvar = case LCSG.lookupGlobal mvar (st ^. LCSE.stateTree . LCSE.actFrame . LCS.gpGlobals) of Just mem -> return mem Nothing -> PP.panic PP.InlineCallee "getMem" ["Global heap value not initialized: " ++ show mvar] setMem :: LCS.CrucibleState s sym ext rtp blocks r ctx -> LCS.GlobalVar (LCT.IntrinsicType nm args) -> LCSI.Intrinsic sym nm args -> LCS.CrucibleState s sym ext rtp blocks r ctx setMem st mvar mem = st & LCSE.stateTree . LCSE.actFrame . LCS.gpGlobals %~ LCSG.insertGlobal mvar mem memReprToStorageType :: (HasCallStack) => DMC.MemRepr ty -> IO LCLM.StorageType memReprToStorageType memRep = case memRep of DMC.BVMemRepr bytes _endian -> do return $ LCLM.bitvectorType (LCLB.Bytes (PN.intValue bytes)) DMC.FloatMemRepr floatRep _endian -> do case floatRep of DMC.SingleFloatRepr -> return LCLM.floatType DMC.DoubleFloatRepr -> return LCLM.doubleType DMC.X86_80FloatRepr -> return LCLM.x86_fp80Type _ -> PP.panic PP.InlineCallee "memReprToStorageType" [ "Do not support memory accesses to " ++ show floatRep ++ " values"] DMC.PackedVecMemRepr n eltType -> do eltStorageType <- memReprToStorageType eltType return $ LCLM.arrayType (PN.natValue n) eltStorageType resolveMemVal :: (HasCallStack) => DMC.MemRepr ty -> LCLM.StorageType -> LCS.RegValue sym (DMS.ToCrucibleType ty) -> LCLM.LLVMVal sym resolveMemVal (DMC.BVMemRepr bytes _endian) _ (LCLM.LLVMPointer base bits) = case PN.leqMulPos (PN.knownNat @8) bytes of PN.LeqProof -> LCLM.LLVMValInt base bits resolveMemVal (DMC.FloatMemRepr floatRep _endian) _ val = case floatRep of DMC.SingleFloatRepr -> LCLM.LLVMValFloat LCLM.SingleSize val DMC.DoubleFloatRepr -> LCLM.LLVMValFloat LCLM.DoubleSize val DMC.X86_80FloatRepr -> LCLM.LLVMValFloat LCLM.X86_FP80Size val _ -> PP.panic PP.InlineCallee "resolveMemVal" ["Do not support memory accesses to " ++ show floatRep ++ " values"] resolveMemVal (DMC.PackedVecMemRepr n eltType) stp val = case LCLM.storageTypeF stp of LCLM.Array cnt eltStp | cnt == PN.natValue n, fromIntegral (V.length val) == PN.natValue n -> LCLM.LLVMValArray eltStp (resolveMemVal eltType eltStp <$> val) _ -> PP.panic PP.InlineCallee "resolveMemVal" ["Unexpected storage type for packed vec"] memValToCrucible :: ( LCB.IsSymInterface sym ) => DMC.MemRepr ty -> LCLM.LLVMVal sym -> Either String (LCS.RegValue sym (DMS.ToCrucibleType ty)) memValToCrucible memRep val = case memRep of DMC.BVMemRepr bytes _endian -> do let bitw = PN.natMultiply (PN.knownNat @8) bytes case val of LCLM.LLVMValInt base off | Just PC.Refl <- PC.testEquality (WI.bvWidth off) bitw -> pure (LCLM.LLVMPointer base off) _ -> unexpectedMemVal DMC.FloatMemRepr floatRep _endian -> case val of LCLM.LLVMValFloat sz fltVal -> case (floatRep, sz) of (DMC.SingleFloatRepr, LCLM.SingleSize) -> pure fltVal (DMC.DoubleFloatRepr, LCLM.DoubleSize) -> pure fltVal (DMC.X86_80FloatRepr, LCLM.X86_FP80Size) -> pure fltVal _ -> unexpectedMemVal _ -> unexpectedMemVal DMC.PackedVecMemRepr _expectedLen eltMemRepr -> do case val of LCLM.LLVMValArray _ v -> do T.traverse (memValToCrucible eltMemRepr) v _ -> unexpectedMemVal where unexpectedMemVal = Left "Unexpected value read from memory" tryGlobPtr :: (LCB.IsSymBackend sym bak) => bak -> LCS.RegValue sym LCLM.Mem -> DMS.GlobalMap sym LCLM.Mem w -> LCLM.LLVMPtr sym w -> IO (LCLM.LLVMPtr sym w) tryGlobPtr bak mem mapBVAddress val@(LCLM.LLVMPointer base offset) | Just blockId <- WI.asNat base , blockId /= 0 = do If we know that the blockId is concretely not zero , the pointer is already translated into an LLVM pointer and can be passed through . return val | otherwise = do If the blockId is zero , we have to translate it into a proper LLVM DMS.applyGlobalMap mapBVAddress bak mem base offset concretizingWrite :: ( LCB.IsSymInterface sym , sym ~ WE.ExprBuilder scope st fs , WPO.OnlineSolver solver , LCLM.HasPtrWidth ptrW , LCLM.HasLLVMAnn sym , ptrW ~ DMC.ArchAddrWidth arch , HasCallStack ) => LCS.GlobalVar LCLM.Mem -> DMS.GlobalMap sym LCLM.Mem ptrW -> LCBO.OnlineBackend solver scope st fs -> LCS.CrucibleState p sym (DMS.MacawExt arch) rtp blocks r ctx -> DMC.AddrWidthRepr ptrW -> DMC.MemRepr ty -> LCS.RegEntry sym (LCLM.LLVMPointerType ptrW) -> LCS.RegEntry sym (DMS.ToCrucibleType ty) -> IO ((), LCS.CrucibleState p sym (DMS.MacawExt arch) rtp blocks r ctx) concretizingWrite memVar globs bak crucState _addrWidth memRep (LCS.regValue -> ptr) (LCS.regValue -> value) = do mem <- getMem crucState memVar ptr' <- tryGlobPtr bak mem globs ptr ptr'' <- PVC.resolveSingletonPointer (PVC.wrappedBackend bak) ptr' ty <- memReprToStorageType memRep let memVal = resolveMemVal memRep ty value mem' <- LCLM.storeRaw bak mem ptr'' ty LCLD.noAlignment memVal return ((), setMem crucState memVar mem') concretizingRead :: ( LCB.IsSymInterface sym , sym ~ WE.ExprBuilder scope st fs , WPO.OnlineSolver solver , LCLM.HasPtrWidth ptrW , ptrW ~ DMC.ArchAddrWidth arch , LCLM.HasLLVMAnn sym , ?memOpts :: LCLM.MemOptions , HasCallStack ) => LCS.GlobalVar LCLM.Mem -> DMS.GlobalMap sym LCLM.Mem ptrW -> LCBO.OnlineBackend solver scope st fs -> LCS.CrucibleState p sym (DMS.MacawExt arch) rtp blocks r ctx -> DMC.AddrWidthRepr ptrW -> DMC.MemRepr ty -> LCS.RegEntry sym (LCLM.LLVMPointerType ptrW) -> IO (LCS.RegValue sym (DMS.ToCrucibleType ty)) concretizingRead memVar globs bak crucState _addrWidth memRep (LCS.regValue -> ptr) = do let sym = LCB.backendGetSym bak mem <- getMem crucState memVar ptr' <- tryGlobPtr bak mem globs ptr ptr''@(LCLM.LLVMPointer _ off) <- PVC.resolveSingletonPointer (PVC.wrappedBackend bak) ptr' case WI.asBV off of Just _ -> do ty <- memReprToStorageType memRep res <- LCLM.assertSafe bak =<< LCLM.loadRaw sym mem ptr'' ty LCLD.noAlignment case memValToCrucible memRep res of Left err -> PP.panic PP.InlineCallee "concretizingRead" [err] Right crucVal -> return crucVal Nothing -> do case memRep of DMC.BVMemRepr nBytesRepr _endianness -> do let bitw = PN.natMultiply (PN.knownNat @8) nBytesRepr case PC.testEquality (WI.bvWidth off) bitw of Just PC.Refl -> do symOff <- WI.freshConstant sym (WS.safeSymbol "symbolicReadBytes") (WT.BaseBVRepr bitw) LCLM.llvmPointer_bv sym symOff _ -> PP.panic PP.InlineCallee "concretizingRead" ["Unsupported memRepr: " ++ show memRep] _ -> PP.panic PP.InlineCallee "concretizingRead" ["Unsupported memRepr: " ++ show memRep] statementWrapper :: ( LCB.IsSymInterface sym , sym ~ WE.ExprBuilder scope st fs , WPO.OnlineSolver solver , LCLM.HasPtrWidth (DMC.ArchAddrWidth arch) , LCLM.HasLLVMAnn sym , ?memOpts :: LCLM.MemOptions , HasCallStack ) => LCS.GlobalVar LCLM.Mem -> DMS.GlobalMap sym LCLM.Mem (DMC.ArchAddrWidth arch) -> LCBO.OnlineBackend solver scope st fs -> LCS.ExtensionImpl p sym (DMS.MacawExt arch) -> DMSB.MacawEvalStmtFunc (LCCE.StmtExtension (DMS.MacawExt arch)) p sym (DMS.MacawExt arch) statementWrapper mvar globs bak baseExt stmt crucState = let sym = LCB.backendGetSym bak in case stmt of DMS.MacawWriteMem addrWidth memRep ptr value -> concretizingWrite mvar globs bak crucState addrWidth memRep ptr value DMS.MacawReadMem addrWidth memRep ptr -> (, crucState) <$> concretizingRead mvar globs bak crucState addrWidth memRep ptr DMS.PtrMux _w (LCS.regValue -> c) (LCS.regValue -> x) (LCS.regValue -> y) -> do ptr <- LCLM.muxLLVMPtr sym c x y return (ptr, crucState) _ -> LCS.extensionExec baseExt stmt crucState | Macaw extensions for Crucible that have some optimizations required for the hookedMacawExtensions :: ( LCB.IsSymInterface sym , sym ~ WE.ExprBuilder scope st fs , WPO.OnlineSolver solver , LCLM.HasLLVMAnn sym , LCLM.HasPtrWidth (DMC.ArchAddrWidth arch) , ?memOpts :: LCLM.MemOptions ) => LCBO.OnlineBackend solver scope st fs -> DMS.MacawArchEvalFn p sym LCLM.Mem arch -> LCS.GlobalVar LCLM.Mem -> DMS.GlobalMap sym LCLM.Mem (DMC.ArchAddrWidth arch) -> DMS.LookupFunctionHandle p sym arch -> DMS.LookupSyscallHandle p sym arch -> DMS.MkGlobalPointerValidityAssertion sym (DMC.ArchAddrWidth arch) -> LCS.ExtensionImpl p sym (DMS.MacawExt arch) hookedMacawExtensions bak f mvar globs lookupH lookupSyscall toMemPred = baseExtension { LCS.extensionExec = statementWrapper mvar globs bak baseExtension } where baseExtension = DMS.macawExtensions f mvar globs lookupH lookupSyscall toMemPred
d9dead01d23e82e74aacd4f242b32d4930dea9afae6fcdb631f0948255f425dc
korya/efuns
sound.ml
(***********************************************************************) (* *) (* ____ *) (* *) Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt (* *) Copyright 1999 Institut National de Recherche en Informatique et Automatique . Distributed only by permission . (* *) (***********************************************************************) type sound = string open Options let use_sound = define_option ["use_sound"] "<use_sound> is true if you want GwML to play sounds for some user actions." bool_option false let use_local_player = define_option ["use_local_player"] "<use_local_player> is true if you want GwML to use a program on your computer to play sounds instead of the NOT built-in Esd library." bool_option false let sound_load file tag = file let sound_unload sound = () let wav_player = define_option ["wav_player"] "<wav_player> is the command used to play wav files if <use_local_player> is true." string_option "wavp" let path = try Utils.string_to_path (Sys.getenv "PATH") with Not_found -> [] let _ = if !!use_local_player then wav_player =:= ( try Utils.find_in_path path !!wav_player with _ -> try Utils.find_in_path path "wavp" with _ -> try Utils.find_in_path path "wavplay" with _ -> "wavp") let sound_play sound = if !!use_local_player && !!use_sound then ignore (Sys.command (Printf.sprintf "%s %s &" !!wav_player sound)) let file_play string = sound_play string let reconnect string = () let init_sound _ = ()
null
https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/gwml/no_esd/sound.ml
ocaml
********************************************************************* ____ *********************************************************************
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt Copyright 1999 Institut National de Recherche en Informatique et Automatique . Distributed only by permission . type sound = string open Options let use_sound = define_option ["use_sound"] "<use_sound> is true if you want GwML to play sounds for some user actions." bool_option false let use_local_player = define_option ["use_local_player"] "<use_local_player> is true if you want GwML to use a program on your computer to play sounds instead of the NOT built-in Esd library." bool_option false let sound_load file tag = file let sound_unload sound = () let wav_player = define_option ["wav_player"] "<wav_player> is the command used to play wav files if <use_local_player> is true." string_option "wavp" let path = try Utils.string_to_path (Sys.getenv "PATH") with Not_found -> [] let _ = if !!use_local_player then wav_player =:= ( try Utils.find_in_path path !!wav_player with _ -> try Utils.find_in_path path "wavp" with _ -> try Utils.find_in_path path "wavplay" with _ -> "wavp") let sound_play sound = if !!use_local_player && !!use_sound then ignore (Sys.command (Printf.sprintf "%s %s &" !!wav_player sound)) let file_play string = sound_play string let reconnect string = () let init_sound _ = ()
0510c3f090fce44e938ec746ad637526aa6963331cc0971fc3cdd9ec99ef012d
cwmaguire/zombunity-mud
login_test.clj
(ns zombunity.login-test (:use clojure.test) (:require [zombunity.dispatch :as disp] [zombunity.data :as data] [zombunity.data.login-data :as login-data])) (def first-run {"login_state" {:conn_id 1 :num_logins 1 :num_passwords 0} "msg-to-client" {:conn-id 1 :message "enter login:"} "user" {:login "alice", :id 1, :password "1234"}}) (def login-entered {"login_state" {:conn_id 1 :num_logins 1 :num_passwords 1 :login "alice"} "msg-to-client" {:conn-id 1 :message "enter password:"} "user" {:login "alice", :id 1, :password "1234"}}) (def login-succeeded {"msg-to-client" {:conn-id 1 :message "login successful"} "user" {:login "alice", :id 1, :password "1234"} "msg-to-server" {:conn-id 1, :user-id 1, :type :user-logged-in}}) (def first-wrong-password {"login_state" {:conn_id 1 :num_logins 2 :num_passwords 1 :login "alice"} "msg-to-client" {:conn-id 1 :message "enter login:"} "user" {:login "alice", :id 1, :password "1234"}}) (def login-failed {"msg-to-client" {:conn-id 1 :message "enter password:"} "user" {:login "alice", :id 1, :password "1234"} "msg-to-server" {:type "login-max-attempts" :conn-id 1}}) (deftest test-login-success-first-try (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "1234"}}) (disp/dispatch {:type "login" :conn-id 1}) (is (= first-run @login-data/data) "Initial login prompt") (disp/dispatch {:type "alice" :conn-id 1}) (is (= login-entered @login-data/data) "Login entered") (disp/dispatch {:type "1234" :conn-id 1}) (is (= login-succeeded @login-data/data) "Password entered") (is (= nil (get "login_state" @login-data/data)))) (deftest test-login-fail-once-then-succeed (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "1234"}}) (disp/dispatch {:type "login" :conn-id 1}) (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "123" :conn-id 1}) (is (= first-wrong-password @login-data/data) "First failure") (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "1234" :conn-id 1}) (is (= login-succeeded @login-data/data) "Success after first failure")) (deftest test-login-fail (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "1234"}}) (disp/dispatch {:type :login :conn-id 1}) (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "wrong password" :conn-id 1}) (disp/dispatch {:type "bob" :conn-id 1}) (disp/dispatch {:type "1234" :conn-id 1}) (disp/dispatch {:type "" :conn-id 1}) (disp/dispatch {:type "wrong password" :conn-id 1}) (is (= login-failed @login-data/data) "Password entered"))
null
https://raw.githubusercontent.com/cwmaguire/zombunity-mud/ec14406f4addac9b9a0742d3043a6e7bccef1fa6/zombunity_server/test/zombunity/login_test.clj
clojure
(ns zombunity.login-test (:use clojure.test) (:require [zombunity.dispatch :as disp] [zombunity.data :as data] [zombunity.data.login-data :as login-data])) (def first-run {"login_state" {:conn_id 1 :num_logins 1 :num_passwords 0} "msg-to-client" {:conn-id 1 :message "enter login:"} "user" {:login "alice", :id 1, :password "1234"}}) (def login-entered {"login_state" {:conn_id 1 :num_logins 1 :num_passwords 1 :login "alice"} "msg-to-client" {:conn-id 1 :message "enter password:"} "user" {:login "alice", :id 1, :password "1234"}}) (def login-succeeded {"msg-to-client" {:conn-id 1 :message "login successful"} "user" {:login "alice", :id 1, :password "1234"} "msg-to-server" {:conn-id 1, :user-id 1, :type :user-logged-in}}) (def first-wrong-password {"login_state" {:conn_id 1 :num_logins 2 :num_passwords 1 :login "alice"} "msg-to-client" {:conn-id 1 :message "enter login:"} "user" {:login "alice", :id 1, :password "1234"}}) (def login-failed {"msg-to-client" {:conn-id 1 :message "enter password:"} "user" {:login "alice", :id 1, :password "1234"} "msg-to-server" {:type "login-max-attempts" :conn-id 1}}) (deftest test-login-success-first-try (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "1234"}}) (disp/dispatch {:type "login" :conn-id 1}) (is (= first-run @login-data/data) "Initial login prompt") (disp/dispatch {:type "alice" :conn-id 1}) (is (= login-entered @login-data/data) "Login entered") (disp/dispatch {:type "1234" :conn-id 1}) (is (= login-succeeded @login-data/data) "Password entered") (is (= nil (get "login_state" @login-data/data)))) (deftest test-login-fail-once-then-succeed (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "1234"}}) (disp/dispatch {:type "login" :conn-id 1}) (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "123" :conn-id 1}) (is (= first-wrong-password @login-data/data) "First failure") (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "1234" :conn-id 1}) (is (= login-succeeded @login-data/data) "Success after first failure")) (deftest test-login-fail (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "1234"}}) (disp/dispatch {:type :login :conn-id 1}) (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "wrong password" :conn-id 1}) (disp/dispatch {:type "bob" :conn-id 1}) (disp/dispatch {:type "1234" :conn-id 1}) (disp/dispatch {:type "" :conn-id 1}) (disp/dispatch {:type "wrong password" :conn-id 1}) (is (= login-failed @login-data/data) "Password entered"))
1a70fea95cc333606e6807b3f71ccf6d444e984499fb20034f1a340117147ea7
marksteele/cinched
cinched_crypto_blob_rest_handler.erl
%%%------------------------------------------------------------------- @author < > ( C ) 2016 , %%% @doc REST API %%% @end Created : 24 Jan 2016 by < > %%%------------------------------------------------------------------- This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. -module(cinched_crypto_blob_rest_handler). -include("cinched.hrl"). %% Callbacks for REST API -export([init/3, known_methods/2, allowed_methods/2, content_types_provided/2, is_authorized/2, content_types_accepted/2]). %% Custom functions -export([encrypt/2, decrypt/2]). -spec init(_,_,_) -> {'upgrade','protocol','cowboy_rest'}. init(_Transport, _Req, _Args) -> {upgrade, protocol, cowboy_rest}. -spec known_methods(_,_) -> {[<<_:32>>,...],_,_}. known_methods(Req, Ctx) -> {[<<"POST">>], Req, Ctx}. -spec allowed_methods(_,_) -> {[<<_:32>>,...],_,_}. allowed_methods(Req, Ctx) -> {[<<"POST">>], Req, Ctx}. -spec is_authorized(_,_) -> {true,any(),any()}. is_authorized(Req,Ctx) -> {true, Req, Ctx}. %% TODO: Save this state (the action) for the content types provided function content_types_accepted(Req, Ctx) -> case cowboy_req:binding(action, Req) of {undefined,Req} -> {halt,Req,{}}; {<<"encrypt">>,Req} -> {[{{<<"application">>, <<"octet-stream">>, '*'}, encrypt}], Req, Ctx}; {<<"decrypt">>,Req} -> {[{{<<"application">>, <<"octet-stream">>, '*'}, decrypt}], Req, Ctx} end. content_types_provided(Req, Ctx) -> case cowboy_req:binding(action, Req) of {undefined,Req} -> {halt,Req,{}}; {<<"encrypt">>,Req} -> {[{{<<"application">>, <<"octet-stream">>, '*'}, encrypt}], Req, Ctx}; {<<"decrypt">>,Req} -> {[{{<<"application">>, <<"octet-stream">>, '*'}, decrypt}], Req, Ctx} end. encrypt(Req0, _Ctx) -> {ok, Body, Req1} = cowboy_req:body(Req0,[]), {ok, DataKey} = case cowboy_req:header(<<"x-cinched-data-key">>, Req1) of {undefined,Req2} -> cinched:generate_data_key(); {KeyHeader,Req2} -> {ok, binary_to_term(base64:decode(KeyHeader))} end, {Time, Value} = timer:tc( fun() -> poolboy:transaction( pb, fun(Worker) -> gen_server:call(Worker,{encrypt,DataKey,Body}) end ) end ), %% Gather logging data {Peer,Port0} = cowboy_req:get(peer,Req2), Port = integer_to_binary(Port0), PeerIP = list_to_binary(inet_parse:ntoa(Peer)), {ok,{Serial,PeerCN}} = cinched:get_cert_info_from_socket(cowboy_req:get(socket,Req2)), {QueryString,Req3} = cowboy_req:qs(Req2), {UserAgent,Req4} = cowboy_req:header(<<"user-agent">>,Req3), {Metadata,Req5} = cowboy_req:header(<<"x-cinched-metadata">>,Req4), exometer:update([crypto_worker,encrypt,time],Time), case Value of {ok, Response} -> cinched_log:log([ {op,blob_encrypt}, {status,ok}, {meta,Metadata}, {query_string,QueryString}, {user_agent,UserAgent}, {peer_ip,PeerIP}, {peer_port,Port}, {peer_cert_cn,PeerCN}, {peer_cert_serial,Serial} ]), Req6 = cowboy_req:set_resp_header( <<"x-cinched-data-key">>, base64:encode(term_to_binary(DataKey)), Req5 ), Req7 = cowboy_req:set_resp_header( <<"x-cinched-crypto-period">>, integer_to_binary(DataKey#cinched_key.crypto_period), Req6 ), exometer:update([api,blob,encrypt,ok],1), {true, cowboy_req:set_resp_body(Response, Req7), {}}; {error,_Err} -> cinched_log:log([ {op,blob_encrypt}, {status,error}, {meta,Metadata}, {query_string,QueryString}, {user_agent,UserAgent}, {peer_ip,PeerIP}, {peer_port,Port}, {peer_cert_cn,PeerCN}, {peer_cert_serial,Serial} ]), exometer:update([api,blob,encrypt,error],1), {false, Req5, {}} end. -spec decrypt(_,_) -> {'true',_,{}}. decrypt(Req0, _Ctx) -> {ok, Body, Req1} = cowboy_req:body(Req0,[]), {ok, DataKey} = case cowboy_req:header(<<"x-cinched-data-key">>, Req1) of {undefined,Req2} -> throw("Error, missing data key"); {KeyHeader,Req2} -> {ok, binary_to_term(base64:decode(KeyHeader))} end, {Time, Value} = timer:tc( fun() -> poolboy:transaction( pb, fun(Worker) -> gen_server:call(Worker,{decrypt,DataKey,Body}) end ) end ), exometer:update([crypto_worker,decrypt,time],Time), %% Gather logging data {Peer,Port0} = cowboy_req:get(peer,Req2), Port = integer_to_binary(Port0), PeerIP = list_to_binary(inet_parse:ntoa(Peer)), {ok,{Serial,PeerCN}} = cinched:get_cert_info_from_socket(cowboy_req:get(socket,Req2)), {QueryString,Req3} = cowboy_req:qs(Req2), {UserAgent,Req4} = cowboy_req:header(<<"user-agent">>,Req3), {Metadata,Req5} = cowboy_req:header(<<"x-cinched-metadata">>,Req4), case Value of {ok, Response} -> cinched_log:log([ {op,blob_decrypt}, {status,ok}, {meta,Metadata}, {query_string,QueryString}, {user_agent,UserAgent}, {peer_ip,PeerIP}, {peer_port,Port}, {peer_cert_cn,PeerCN}, {peer_cert_serial,Serial} ]), exometer:update([api,blob,decrypt,ok],1), {true,cowboy_req:set_resp_body(Response,Req5), {}}; {error,_} -> cinched_log:log([ {op,blob_decrypt}, {status,error}, {meta,Metadata}, {query_string,QueryString}, {user_agent,UserAgent}, {peer_ip,PeerIP}, {peer_port,Port}, {peer_cert_cn,PeerCN}, {peer_cert_serial,Serial} ]), exometer:update([api,blob,decrypt,error],1), {halt, Req5, {}} end.
null
https://raw.githubusercontent.com/marksteele/cinched/5284d048c649128fa8929f6e85cdc4747d223427/src/cinched_crypto_blob_rest_handler.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Callbacks for REST API Custom functions TODO: Save this state (the action) for the content types provided function Gather logging data Gather logging data
@author < > ( C ) 2016 , REST API Created : 24 Jan 2016 by < > This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(cinched_crypto_blob_rest_handler). -include("cinched.hrl"). -export([init/3, known_methods/2, allowed_methods/2, content_types_provided/2, is_authorized/2, content_types_accepted/2]). -export([encrypt/2, decrypt/2]). -spec init(_,_,_) -> {'upgrade','protocol','cowboy_rest'}. init(_Transport, _Req, _Args) -> {upgrade, protocol, cowboy_rest}. -spec known_methods(_,_) -> {[<<_:32>>,...],_,_}. known_methods(Req, Ctx) -> {[<<"POST">>], Req, Ctx}. -spec allowed_methods(_,_) -> {[<<_:32>>,...],_,_}. allowed_methods(Req, Ctx) -> {[<<"POST">>], Req, Ctx}. -spec is_authorized(_,_) -> {true,any(),any()}. is_authorized(Req,Ctx) -> {true, Req, Ctx}. content_types_accepted(Req, Ctx) -> case cowboy_req:binding(action, Req) of {undefined,Req} -> {halt,Req,{}}; {<<"encrypt">>,Req} -> {[{{<<"application">>, <<"octet-stream">>, '*'}, encrypt}], Req, Ctx}; {<<"decrypt">>,Req} -> {[{{<<"application">>, <<"octet-stream">>, '*'}, decrypt}], Req, Ctx} end. content_types_provided(Req, Ctx) -> case cowboy_req:binding(action, Req) of {undefined,Req} -> {halt,Req,{}}; {<<"encrypt">>,Req} -> {[{{<<"application">>, <<"octet-stream">>, '*'}, encrypt}], Req, Ctx}; {<<"decrypt">>,Req} -> {[{{<<"application">>, <<"octet-stream">>, '*'}, decrypt}], Req, Ctx} end. encrypt(Req0, _Ctx) -> {ok, Body, Req1} = cowboy_req:body(Req0,[]), {ok, DataKey} = case cowboy_req:header(<<"x-cinched-data-key">>, Req1) of {undefined,Req2} -> cinched:generate_data_key(); {KeyHeader,Req2} -> {ok, binary_to_term(base64:decode(KeyHeader))} end, {Time, Value} = timer:tc( fun() -> poolboy:transaction( pb, fun(Worker) -> gen_server:call(Worker,{encrypt,DataKey,Body}) end ) end ), {Peer,Port0} = cowboy_req:get(peer,Req2), Port = integer_to_binary(Port0), PeerIP = list_to_binary(inet_parse:ntoa(Peer)), {ok,{Serial,PeerCN}} = cinched:get_cert_info_from_socket(cowboy_req:get(socket,Req2)), {QueryString,Req3} = cowboy_req:qs(Req2), {UserAgent,Req4} = cowboy_req:header(<<"user-agent">>,Req3), {Metadata,Req5} = cowboy_req:header(<<"x-cinched-metadata">>,Req4), exometer:update([crypto_worker,encrypt,time],Time), case Value of {ok, Response} -> cinched_log:log([ {op,blob_encrypt}, {status,ok}, {meta,Metadata}, {query_string,QueryString}, {user_agent,UserAgent}, {peer_ip,PeerIP}, {peer_port,Port}, {peer_cert_cn,PeerCN}, {peer_cert_serial,Serial} ]), Req6 = cowboy_req:set_resp_header( <<"x-cinched-data-key">>, base64:encode(term_to_binary(DataKey)), Req5 ), Req7 = cowboy_req:set_resp_header( <<"x-cinched-crypto-period">>, integer_to_binary(DataKey#cinched_key.crypto_period), Req6 ), exometer:update([api,blob,encrypt,ok],1), {true, cowboy_req:set_resp_body(Response, Req7), {}}; {error,_Err} -> cinched_log:log([ {op,blob_encrypt}, {status,error}, {meta,Metadata}, {query_string,QueryString}, {user_agent,UserAgent}, {peer_ip,PeerIP}, {peer_port,Port}, {peer_cert_cn,PeerCN}, {peer_cert_serial,Serial} ]), exometer:update([api,blob,encrypt,error],1), {false, Req5, {}} end. -spec decrypt(_,_) -> {'true',_,{}}. decrypt(Req0, _Ctx) -> {ok, Body, Req1} = cowboy_req:body(Req0,[]), {ok, DataKey} = case cowboy_req:header(<<"x-cinched-data-key">>, Req1) of {undefined,Req2} -> throw("Error, missing data key"); {KeyHeader,Req2} -> {ok, binary_to_term(base64:decode(KeyHeader))} end, {Time, Value} = timer:tc( fun() -> poolboy:transaction( pb, fun(Worker) -> gen_server:call(Worker,{decrypt,DataKey,Body}) end ) end ), exometer:update([crypto_worker,decrypt,time],Time), {Peer,Port0} = cowboy_req:get(peer,Req2), Port = integer_to_binary(Port0), PeerIP = list_to_binary(inet_parse:ntoa(Peer)), {ok,{Serial,PeerCN}} = cinched:get_cert_info_from_socket(cowboy_req:get(socket,Req2)), {QueryString,Req3} = cowboy_req:qs(Req2), {UserAgent,Req4} = cowboy_req:header(<<"user-agent">>,Req3), {Metadata,Req5} = cowboy_req:header(<<"x-cinched-metadata">>,Req4), case Value of {ok, Response} -> cinched_log:log([ {op,blob_decrypt}, {status,ok}, {meta,Metadata}, {query_string,QueryString}, {user_agent,UserAgent}, {peer_ip,PeerIP}, {peer_port,Port}, {peer_cert_cn,PeerCN}, {peer_cert_serial,Serial} ]), exometer:update([api,blob,decrypt,ok],1), {true,cowboy_req:set_resp_body(Response,Req5), {}}; {error,_} -> cinched_log:log([ {op,blob_decrypt}, {status,error}, {meta,Metadata}, {query_string,QueryString}, {user_agent,UserAgent}, {peer_ip,PeerIP}, {peer_port,Port}, {peer_cert_cn,PeerCN}, {peer_cert_serial,Serial} ]), exometer:update([api,blob,decrypt,error],1), {halt, Req5, {}} end.
8d7e25129f4b07ac6c1633215663fdbaf4dedd8da1771a93927d95f6cfe76d4b
rvirding/luerl
luerl_emul.erl
Copyright ( c ) 2013 - 2020 %% 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. %% File : luerl_emul.erl Author : Purpose : A basic LUA 5.3 machine emulator . First version of emulator . Compiler so far only explicitly handles %% local/global variables. %% We explicitly mirror the parser rules which generate the AST and do %% not try to fold similar structures into common code. While this %% means we get more code it also becomes more explicit and clear what %% we are doing. It may also allow for specific optimisations. And %% example is that we DON'T fold 'var' and 'funcname' even though they %% are almost the same. %% %% Issues: how should we handle '...'? Now we treat it as any (local) %% variable. -module(luerl_emul). -include("luerl.hrl"). -include("luerl_comp.hrl"). -include("luerl_instrs.hrl"). %% Basic interface. -export([init/0,gc/1]). -export([call/2,call/3,emul/2]). -export([load_chunk/2,load_chunk/3]). -export([functioncall/3,methodcall/4, set_global_key/3,get_global_key/2, get_table_keys/2,get_table_keys/3, set_table_keys/3,set_table_keys/4, get_table_key/3,set_table_key/4 ]). %% Temporary shadow calls. -export([alloc_table/2,set_userdata/3,get_metamethod/3]). %% For testing. -export([pop_vals/2,push_vals/3]). -import(luerl_lib, [lua_error/2,badarg_error/3]). %% -compile(inline). %For when we are optimising %% -compile({inline,[boolean_value/1,first_value/1]}). %% -define(ITRACE_DO(Expr), ok). -define(ITRACE_DO(Expr), begin (get(luerl_itrace) /= undefined) andalso Expr end). %% Temporary shadow calls. gc(St) -> luerl_heap:gc(St). alloc_table(Itab, St) -> luerl_heap:alloc_table(Itab, St). set_userdata(Ref, Data, St) -> luerl_heap:set_userdata(Ref, Data, St). get_metamethod(Obj, Event, St) -> luerl_heap:get_metamethod(Obj, Event, St). %% init() -> State. Initialise the basic state . init() -> St1 = luerl_heap:init(), %% Allocate the _G table and initialise the environment {_G,St2} = luerl_lib_basic:install(St1), %Global environment St3 = St2#luerl{g=_G}, Now we can start adding libraries . Package MUST be first ! St4 = load_lib(<<"package">>, luerl_lib_package, St3), %% Add the other standard libraries. St5 = load_libs([ {<<"bit32">>,luerl_lib_bit32}, {<<"io">>,luerl_lib_io}, {<<"math">>,luerl_lib_math}, {<<"os">>,luerl_lib_os}, {<<"string">>,luerl_lib_string}, {<<"utf8">>,luerl_lib_utf8}, {<<"table">>,luerl_lib_table}, {<<"debug">>,luerl_lib_debug} ], St4), %% Set _G variable to point to it and add it to packages.loaded. St6 = set_global_key(<<"_G">>, _G, St5), set_table_keys([<<"package">>,<<"loaded">>,<<"_G">>], _G, St6). load_libs(Libs, St) -> Fun = fun ({Key,Mod}, S) -> load_lib(Key, Mod, S) end, lists:foldl(Fun, St, Libs). load_lib(Key , Module , State ) - > State . load_lib(Key, Mod, St0) -> {Tab,St1} = Mod:install(St0), %% Add key to global and to package.loaded. St2 = set_global_key(Key, Tab, St1), set_table_keys([<<"package">>,<<"loaded">>,Key], Tab, St2). set_global_key(Key , Value , State ) - > State . get_global_key(Key , State ) - > { [ Val],State } . %% Access elements in the global name table, _G. set_global_key(Key, Val, #luerl{g=G}=St) -> set_table_key(G, Key, Val, St). get_global_key(Key, #luerl{g=G}=St) -> get_table_key(G, Key, St). get_table_keys(Keys , State ) - > { Value , State } . get_table_keys(Tab , Keys , State ) - > { Value , State } . %% Search down tables which stops when no more tables. get_table_keys(Keys, St) -> get_table_keys(St#luerl.g, Keys, St). get_table_keys(Tab, [K|Ks], St0) -> {Val,St1} = get_table_key(Tab, K, St0), get_table_keys(Val, Ks, St1); get_table_keys(Val, [], St) -> {Val,St}. set_table_keys(Keys , , State ) - > State . set_table_keys(Tab , Keys , , State ) - > State . %% Setter down tables. set_table_keys(Keys, Val, St) -> set_table_keys(St#luerl.g, Keys, Val, St). set_table_keys(Tab, [K], Val, St) -> set_table_key(Tab, K, Val, St); set_table_keys(Tab0, [K|Ks], Val, St0) -> {Tab1,St1} = get_table_key(Tab0, K, St0), set_table_keys(Tab1, Ks, Val, St1). set_table_key(Tref , Key , Value , State ) - > State . get_table_key(Tref , Key , State ) - > { Val , State } . %% Access tables, as opposed to the environment (which are also %% tables). Setting a value to 'nil' will clear it from the array but %% not from the table; however, we won't add a nil value. %% NOTE: WE ALWAYS RETURN A SINGLE VALUE! set_table_key(Tref, Key, Val, St0) -> case luerl_heap:set_table_key(Tref, Key, Val, St0) of {value,_Val,St1} -> St1; {meta,Meth,Args,St1} -> {_Ret,St2} = functioncall(Meth, Args, St1), St2; {error,Error,St1} -> lua_error(Error, St1) end. get_table_key(Tref, Key, St0) -> case luerl_heap:get_table_key(Tref, Key, St0) of {value,Val,St1} -> {Val,St1}; {meta,Meth,Args,St1} -> {Ret,St2} = functioncall(Meth, Args, St1), {first_value(Ret),St2}; {error,Error,St1} -> lua_error(Error, St1) end. set_local_var(Depth , Index , Var , Frames ) - > Frames . %% get_local_var(Depth, Index, Frames) -> Val. set_local_var(1, I, V, [F|Fs]) -> [setelement(I, F, V)|Fs]; set_local_var(D, I, V, [F|Fs]) -> [F|set_local_var(D-1, I, V, Fs)]. get_local_var(1, I, [F|_]) -> element(I, F); get_local_var(D, I, [_|Fs]) -> get_local_var(D-1, I, Fs). set_env_var(Depth , Index , , EnvStack , State ) - > State . get_env_var(Depth , Index , EnvStack , State ) - > Val . %% We must have the state as the environments are global in the %% state. set_env_var(D, I, Val, Estk, St) -> St1 = set_env_var_1(D, I, Val, Estk, St), %% io:format("******** SEV DONE ~w ~w ********\n", [D,I]), St1. set_env_var_1(1, I, Val, [Eref|_], St) -> luerl_heap:set_env_var(Eref, I, Val, St); set_env_var_1(2, I, Val, [_,Eref|_], St) -> luerl_heap:set_env_var(Eref, I, Val, St); set_env_var_1(D, I, Val, Env, St) -> luerl_heap:set_env_var(lists:nth(D, Env), I, Val, St). get_env_var(D, I, Env, St) -> Val = get_env_var_1(D, I, Env, St), %% io:format("******** GEV DONE ~w ~w ********\n", [D, I]), Val. get_env_var_1(1, I, [Eref|_], St) -> luerl_heap:get_env_var(Eref, I, St); get_env_var_1(2, I, [_,Eref|_], St) -> luerl_heap:get_env_var(Eref, I, St); get_env_var_1(D, I, Env, St) -> luerl_heap:get_env_var(lists:nth(D, Env), I, St). load_chunk(FunctionDefCode , State ) - > { Function , State } . %% load_chunk(FunctionDefCode, Env, State) -> {Function,State}. %% Load a chunk from the compiler which is a compiled function %% definition whose instructions define everything. Return a callable function reference which defines everything and a updated Luerl %% state. load_chunk(Code, St) -> load_chunk(Code, [], St). load_chunk([Code], [], St0) -> {?PUSH_FDEF(Funref),_,St1} = load_chunk_i(Code, [], St0), {Funref,St1}. %% load_chunk_i(Instr, FuncRefs, Status) -> {Instr,FuncRefs,State}. load_chunk_is(Instrs , FuncRefs , Status ) - > { Instrs , FuncRefs , State } . %% Load chunk instructions. We keep track of the functions refs and %% save the ones directly accessed in each function. This will make %% gc easier as we will not have to step through the function code at %% gc time. load_chunk_is([I0|Is0], Funrs0, St0) -> {I1,Funrs1,St1} = load_chunk_i(I0, Funrs0, St0), {Is1,Funrs2,St2} = load_chunk_is(Is0, Funrs1, St1), {[I1|Is1],Funrs2,St2}; load_chunk_is([], Funrs, St) -> {[],Funrs,St}. First the instructions with nested code . %% We include the dymanmic instructions here even though the compiler %% does not generate them. This should make us more future proof. load_chunk_i(?PUSH_FDEF(Anno, Lsz, Esz, Pars, B0), Funrs0, St0) -> {B1,Funrs,St1} = load_chunk_is(B0, [], St0), Fdef = #lua_func{anno=Anno,funrefs=Funrs,lsz=Lsz,esz=Esz,pars=Pars,body=B1}, {Funref,St2} = luerl_heap:alloc_funcdef(Fdef, St1), Funrs1 = ordsets:add_element(Funref, Funrs0), {?PUSH_FDEF(Funref),Funrs1,St2}; load_chunk_i(?BLOCK(Lsz, Esz, B0), Funrs0, St0) -> {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?BLOCK(Lsz, Esz, B1),Funrs1,St1}; load_chunk_i(?REPEAT(B0), Funrs0, St0) -> {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?REPEAT(B1),Funrs1,St1}; load_chunk_i(?REPEAT_LOOP(B0), Funrs0, St0) -> %This is dynamic {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?REPEAT_LOOP(B1),Funrs1,St1}; load_chunk_i(?WHILE(E0, B0), Funrs0, St0) -> {E1,Funrs1,St1} = load_chunk_is(E0, Funrs0, St0), {B1,Funrs2,St2} = load_chunk_is(B0, Funrs1, St1), {?WHILE(E1, B1),Funrs2,St2}; load_chunk_i(?WHILE_LOOP(E0, B0), Funrs0, St0) -> {E1,Funrs1,St1} = load_chunk_is(E0, Funrs0, St0), {B1,Funrs2,St2} = load_chunk_is(B0, Funrs1, St1), {?WHILE_LOOP(E1, B1),Funrs2,St2}; load_chunk_i(?AND_THEN(T0), Funrs0, St0) -> {T1,Funrs1,St1} = load_chunk_is(T0, Funrs0, St0), {?AND_THEN(T1),Funrs1,St1}; load_chunk_i(?OR_ELSE(T0), Funrs0, St0) -> {T1,Funrs1,St1} = load_chunk_is(T0, Funrs0, St0), {?OR_ELSE(T1),Funrs1,St1}; load_chunk_i(?IF_TRUE(T0), Funrs0, St0) -> {T1,Funrs1,St1} = load_chunk_is(T0, Funrs0, St0), {?IF_TRUE(T1),Funrs1,St1}; load_chunk_i(?IF(T0, F0), Funrs0, St0) -> {T1,Funrs1,St1} = load_chunk_is(T0, Funrs0, St0), {F1,Funrs2,St2} = load_chunk_is(F0, Funrs1, St1), {?IF(T1, F1),Funrs2,St2}; load_chunk_i(?NFOR(V, B0), Funrs0, St0) -> {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?NFOR(V, B1),Funrs1,St1}; load_chunk_i(?NFOR_LOOP(N, L, S, B0), Funrs0, St0) -> %This is dynamic {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?NFOR_LOOP(N, L, S, B1),Funrs1,St1}; load_chunk_i(?GFOR(Vs, B0), Funrs0, St0) -> {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?GFOR(Vs, B1),Funrs1,St1}; load_chunk_i(?GFOR_CALL(F, D, V, B0), Funrs0, St0) -> %This is dynamic {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?GFOR_CALL(F, D, V, B1),Funrs1,St1}; load_chunk_i(?GFOR_LOOP(F, D, B0), Funrs0, St0) -> %This is dynamic {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?GFOR_LOOP(F, D, B1),Funrs1,St1}; %% Then the rest which we don't have to worry about. load_chunk_i(I, Funrs, St) -> {I,Funrs,St}. call(Function , State ) - > { Return , State } . call(Function , , State ) - > { Return , State } . functioncall(Function , , State ) - > { Return , State } . methodcall(Object , Method , , State ) - > { Return , State } . %% These ares called from the outside and expect everything necessary %% to be in the state. call(Func, St) -> call(Func, [], St). call(#funref{}=Funref, Args, St0) -> %Lua function {Ret,St1} = functioncall(Funref, Args, St0), Should do GC here . {Ret,St1}; Erlang function {Ret,St1} = functioncall(Func, Args, St0), Should do GC here . {Ret,St1}. functioncall(Func, Args, #luerl{stk=Stk}=St0) -> Fr = #call_frame{func=Func,args=Args,lvs=[],env=[],is=[],cont=[]}, Cs0 = [Fr], {_Lvs,[Ret|_],_Env,Cs1,St1} = call_function(Func, Args, Stk, Cs0, St0), {Ret,St1#luerl{stk=Stk,cs=Cs1}}. %Reset the stacks methodcall(Obj, Meth, Args, St0) -> %% Get the function to call from object and method. case get_table_key(Obj, Meth, St0) of {nil,St1} -> %No method lua_error({undefined_method,Obj,Meth}, St1); {Func,St1} -> functioncall(Func, [Obj|Args], St1) end. emul(Instrs , State ) . emul(Instrs , Continuation , LocalVariables , Stack , Env , CallStack , State ) . %% The cost of checking the itrace process variable is very slight %% compared to everythin else. emul(Is, St) -> emul(Is, [], {}, [], [], [], St). %% The faster (yeah sure) version. %% emul(Is, Cont, Lvs, Stk, Env, Cs, St) -> %% emul_1(Is, Cont, Lvs, Stk, Env, Cs, St). %% The tracing versions. emul([I|_]=Is, Cont, Lvs, Stk, Env, Cs, St) -> ?ITRACE_DO(begin io:fwrite("Is: ~p\n", [Is]), io:fwrite("Cnt: ~p\n", [Cont]), io:fwrite("Lvs: ~p\n", [Lvs]), io:fwrite("Env: ~p\n", [Env]), io:fwrite("Stk: ~p\n", [Stk]), io:fwrite("Cs: ~p\n", [Cs]), io:fwrite("I: ~p\n", [I]), io:put_chars("--------\n") end), emul_1(Is, Cont, Lvs, Stk, Env, Cs, St); emul([], Cont, Lvs, Stk, Env, Cs, St) -> ?ITRACE_DO(begin io:fwrite("Is: ~p\n", [[]]), io:fwrite("Cnt: ~p\n", [Cont]), io:fwrite("Lvs: ~p\n", [Lvs]), io:fwrite("Env: ~p\n", [Env]), io:fwrite("Stk: ~p\n", [Stk]), io:fwrite("Cs: ~p\n", [Cs]), io:put_chars("--------\n") end), emul_1([], Cont, Lvs, Stk, Env, Cs, St). itrace_print(Format , ) - > ? ITRACE_DO(io : fwrite(Format , ) ) . %% Expression instructions. emul_1([?PUSH_LIT(L)|Is], Cont, Lvs, Stk, Env, Cs, St) -> emul(Is, Cont, Lvs, [L|Stk], Env, Cs, St); emul_1([?PUSH_LVAR(D, I)|Is], Cont, Lvs, Stk, Env, Cs, St) -> Val = get_local_var(D, I, Lvs), emul(Is, Cont, Lvs, [Val|Stk], Env, Cs, St); emul_1([?PUSH_EVAR(D, I)|Is], Cont, Lvs, Stk, Env, Cs, St) -> Val = get_env_var(D, I, Env, St), emul(Is, Cont, Lvs, [Val|Stk], Env, Cs, St); emul_1([?PUSH_GVAR(Key)|Is], Cont, Lvs, Stk, Env, Cs, St0) -> %% We must handle the metamethod and error here. case luerl_heap:get_global_key(Key, St0) of {value,Val,St1} -> emul(Is, Cont, Lvs, [Val|Stk], Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL,?SINGLE|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end; emul_1([?PUSH_LAST_LIT(L)|Is], Cont, Lvs, Stk, Env, Cs, St) -> emul(Is, Cont, Lvs, [[L]|Stk], Env, Cs, St); emul_1([?PUSH_LAST_LVAR(D, I)|Is], Cont, Lvs, Stk, Env, Cs, St) -> Val = get_local_var(D, I, Lvs), emul(Is, Cont, Lvs, [[Val]|Stk], Env, Cs, St); emul_1([?PUSH_LAST_EVAR(D, I)|Is], Cont, Lvs, Stk, Env, Cs, St) -> Val = get_env_var(D, I, Env, St), emul(Is, Cont, Lvs, [[Val]|Stk], Env, Cs, St); emul_1([?PUSH_LAST_GVAR(Key)|Is], Cont, Lvs, Stk, Env, Cs, St0) -> %% We must handle the metamethod and error here. case luerl_heap:get_global_key(Key, St0) of {value,Val,St1} -> emul(Is, Cont, Lvs, [[Val]|Stk], Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end; emul_1([?STORE_LVAR(D, I)|Is], Cont, Lvs0, [Val|Stk], Env, Cs, St) -> Lvs1 = set_local_var(D, I, Val, Lvs0), emul(Is, Cont, Lvs1, Stk, Env, Cs, St); emul_1([?STORE_EVAR(D, I)|Is], Cont, Lvs, [Val|Stk], Env, Cs, St0) -> St1 = set_env_var(D, I, Val, Env, St0), emul(Is, Cont, Lvs, Stk, Env, Cs, St1); emul_1([?STORE_GVAR(Key)|Is], Cont, Lvs, [Val|Stk], Env, Cs, St0) -> %% We must handle the metamethod and error here. case luerl_heap:set_global_key(Key, Val, St0) of {value,_,St1} -> emul(Is, Cont, Lvs, Stk, Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL,?POP|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end; emul_1([?GET_KEY|Is], Cont, Lvs, [Key,Tab|Stk], Env, Cs, St) -> do_get_key(Is, Cont, Lvs, Stk, Env, Cs, St, Tab, Key); emul_1([?GET_LIT_KEY(Key)|Is], Cont, Lvs, [Tab|Stk], Env, Cs, St) -> %% [?PUSH_LIT(Key),?GET_KEY] do_get_key(Is, Cont, Lvs, Stk, Env, Cs, St, Tab, Key); emul_1([?SET_KEY|Is], Cont, Lvs, [Key,Tab,Val|Stk], Env, Cs, St) -> do_set_key(Is, Cont, Lvs, Stk, Env, Cs, St, Tab, Key, Val); emul_1([?SET_LIT_KEY(Key)|Is], Cont, Lvs, [Tab,Val|Stk], Env, Cs, St) -> %% [?PUSH_LIT(Key),?SET_KEY] do_set_key(Is, Cont, Lvs, Stk, Env, Cs, St, Tab, Key, Val); emul_1([?SINGLE|Is], Cont, Lvs, [Val|Stk], Env, Cs, St) -> emul(Is, Cont, Lvs, [first_value(Val)|Stk], Env, Cs, St); emul_1([?MULTIPLE|Is], Cont, Lvs, [Val|Stk], Env, Cs, St) -> emul(Is, Cont, Lvs, [multiple_value(Val)|Stk], Env, Cs, St); emul_1([?BUILD_TAB(Fc, I)|Is], Cont, Lvs, Stk0, Env, Cs, St0) -> {Tab,Stk1,St1} = build_tab(Fc, I, Stk0, St0), emul(Is, Cont, Lvs, [Tab|Stk1], Env, Cs, St1); emul_1([?FCALL|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_fcall(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([?TAIL_FCALL|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_tail_fcall(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([?MCALL(M)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_mcall(Is, Cont, Lvs, Stk, Env, Cs, St, M); emul_1([?TAIL_MCALL(M)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_tail_mcall(Is, Cont, Lvs, Stk, Env, Cs, St, M); emul_1([?OP(Op,1)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_op1(Is, Cont, Lvs, Stk, Env, Cs, St, Op); emul_1([?OP(Op,2)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_op2(Is, Cont, Lvs, Stk, Env, Cs, St, Op); emul_1([?PUSH_FDEF(Funref)|Is], Cont, Lvs, Stk, Env, Cs, St0) -> %% Update the env field of the function reference with the current %% environment. Funref1 = Funref#funref{env=Env}, emul(Is, Cont, Lvs, [Funref1|Stk], Env, Cs, St0); %% Control instructions. emul_1([?BLOCK(Lsz, Esz, Bis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_block(Is, Cont, Lvs, Stk, Env, Cs, St, Lsz, Esz, Bis); emul_1([?BLOCK_OPEN(Lsz, Esz)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_block_open(Is, Cont, Lvs, Stk, Env, Cs, St, Lsz, Esz); emul_1([?BLOCK_CLOSE|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_block_close(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([?WHILE(Eis, Wis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_while(Is, Cont, Lvs, Stk, Env, Cs, St, Eis, Wis); emul_1([?WHILE_LOOP(Eis, Wis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_while_loop(Is, Cont, Lvs, Stk, Env, Cs, St, Eis, Wis); emul_1([?REPEAT(Ris)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_repeat(Is, Cont, Lvs, Stk, Env, Cs, St, Ris); emul_1([?REPEAT_LOOP(Ris)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_repeat_loop(Is, Cont, Lvs, Stk, Env, Cs, St, Ris); emul_1([?AND_THEN(Then)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_and_then(Is, Cont, Lvs, Stk, Env, Cs, St, Then); emul_1([?OR_ELSE(Else)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_or_else(Is, Cont, Lvs, Stk, Env, Cs, St, Else); emul_1([?IF_TRUE(True)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_if_true(Is, Cont, Lvs, Stk, Env, Cs, St, True); emul_1([?IF(True, False)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_if(Is, Cont, Lvs, Stk, Env, Cs, St, True, False); emul_1([?NFOR(V, Fis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_numfor(Is, Cont, Lvs, Stk, Env, Cs, St, V, Fis); emul_1([?NFOR_LOOP(N,L,S,Fis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_numfor_loop(Is, Cont, Lvs, Stk, Env, Cs, St, N, L, S, Fis); emul_1([?GFOR(Vs, Fis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_genfor(Is, Cont, Lvs, Stk, Env, Cs, St, Vs, Fis); emul_1([?GFOR_CALL(Func, Data, Val, Fis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_genfor_call(Is, Cont, Lvs, Stk, Env, Cs, St, Func, Data, Val, Fis); emul_1([?GFOR_LOOP(Func, Data, Fis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_genfor_loop(Is, Cont, Lvs, Stk, Env, Cs, St, Func, Data, Fis); emul_1([?BREAK|_], _Cont, Lvs, _Stk, _Env, Cs, St) -> do_break(Lvs, Cs, St); emul_1([?RETURN(Ac)|_], _Cont, _Lvs, Stk, _Env, Cs, St) -> do_return(Ac, Stk, Cs, St); Stack instructions emul_1([?POP|Is], Cont, Lvs, [_|Stk], Env, Cs, St) -> emul(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([?POP2|Is], Cont, Lvs, [_,_|Stk], Env, Cs, St) -> emul(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([?SWAP|Is], Cont, Lvs, [S1,S2|Stk], Env, Cs, St) -> emul(Is, Cont, Lvs, [S2,S1|Stk], Env, Cs, St); emul_1([?DUP|Is], Cont, Lvs, [V|_]=Stk, Env, Cs, St) -> emul(Is, Cont, Lvs, [V|Stk], Env, Cs, St); emul_1([?PUSH_VALS(Vc)|Is], Cont, Lvs, [Vals|Stk0], Env, Cs, St) -> Pop value list off the stack and push Vc vals from it . Stk1 = push_vals(Vc, Vals, Stk0), emul(Is, Cont, Lvs, Stk1, Env, Cs, St); emul_1([?POP_VALS(Vc)|Is], Cont, Lvs, Stk0, Env, Cs, St) -> %% Pop Vc vals off the stack, put in a list and push onto the stack. {Vals,Stk1} = pop_vals(Vc, Stk0), emul(Is, Cont, Lvs, [Vals|Stk1], Env, Cs, St); emul_1([?PUSH_ARGS(Al)|Is], Cont, Lvs, [Args|Stk0], Env, Cs, St) -> %% Pop argument list off the stack and push args onto the stack. Stk1 = push_args(Al, Args, Stk0), emul(Is, Cont, Lvs, Stk1, Env, Cs, St); emul_1([?POP_ARGS(Ac)|Is], Cont, Lvs, Stk0, Env, Cs, St) -> %% Pop Ac args off the stack, put in a list and push onto the stack. {Args,Stk1} = pop_vals(Ac, Stk0), emul(Is, Cont, Lvs, [Args|Stk1], Env, Cs, St); emul_1([?COMMENT(_)|Is], Cont, Lvs, Stk, Env, Cs, St) -> %% This just a comment which is ignored. emul(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([?CURRENT_LINE(Line,File)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_current_line(Is, Cont, Lvs, Stk, Env, Cs, St, Line, File); emul_1([], [Is|Cont], Lvs, Stk, Env, Cs, St) -> emul(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([], [], Lvs, Stk, Env, Cs, St) -> {Lvs,Stk,Env,Cs,St}. pop_vals(Count , ) - > { ValList , Stack } . pop_vals(Count , Stack , ValList ) - > { ValList , Stack } . %% Pop Count values off the stack and push onto the value list. First value is deepest . Always generates list . pop_vals(0, Stk) -> {[],Stk}; pop_vals(C, [Vtail|Stk]) -> %This a list tail pop_vals(C-1, Stk, Vtail). pop_vals(0, Stk, Vs) -> {Vs,Stk}; pop_vals(1, [V|Stk], Vs) -> {[V|Vs],Stk}; pop_vals(2, [V2,V1|Stk], Vs) -> {[V1,V2|Vs],Stk}; pop_vals(C, [V2,V1|Stk], Vs) -> pop_vals(C-2, Stk, [V1,V2|Vs]). push_vals(Count , ValList , Stack ) - > Stack . Push Count values from ValList onto the stack . First value is %% deepest. Fill with 'nil' if not enough values. push_vals(0, _, Stk) -> Stk; push_vals(C, [V|Vs], Stk) -> push_vals(C-1, Vs, [V|Stk]); push_vals(C, [], Stk) -> push_vals(C-1, [], [nil|Stk]). push_args(Varlist , ArgList , Stack ) - > Stack . Use Varlist to push args from ArgList onto the stack . First arg is deepest . Tail of VarList determines whether there are . push_args([_V|Vs], [A|As], Stk) -> push_args(Vs, As, [A|Stk]); push_args([_V|Vs], [], Stk) -> push_args(Vs, [], [nil|Stk]); push_args([], _As, Stk) -> Stk; %Drop the rest ... save as list [As|Stk]. do_set_key(Instrs , LocalVars , Stack , Env , State , Table , Key , ) - > %% ReturnFromEmul. do_get_key(Instrs , , Stack , Env , State , Table , Key ) - > %% ReturnFromEmul. do_set_key(Is, Cont, Lvs, Stk, Env, Cs, St0, Tab, Key, Val) -> %% We must handle the metamethod and error here. case luerl_heap:set_table_key(Tab, Key, Val, St0) of {value,_,St1} -> emul(Is, Cont, Lvs, Stk, Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL,?POP|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end. do_get_key(Is, Cont, Lvs, Stk, Env, Cs, St0, Tab, Key) -> %% We must handle the metamethod and error here. case luerl_heap:get_table_key(Tab, Key, St0) of {value,Val,St1} -> emul(Is, Cont, Lvs, [Val|Stk], Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL,?SINGLE|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end. do_op1(Instrs , LocalVars , Stack , Env , State , Op ) - > ReturnFromEmul . do_op2(Instrs , , Stack , Env , State , Op ) - > ReturnFromEmul . do_op1(Is, Cont, Lvs, [A|Stk], Env, Cs, St0, Op) -> %% We must handle the metamethod and error here. case op(Op, A, St0) of {value,Res,St1} -> emul(Is, Cont, Lvs, [Res|Stk], Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL,?SINGLE|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end. do_op2(Is, Cont, Lvs, [A2,A1|Stk], Env, Cs, St0, Op) -> %% We must handle the metamethod and error here. case op(Op, A1, A2, St0) of {value,Res,St1} -> emul(Is, Cont, Lvs, [Res|Stk], Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL,?SINGLE|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end. do_break(LocalVars , CallStack , State ) - > < emul > . do_break(Lvs0, Cs0, St) -> {Bf,Cs1} = find_loop_frame(Cs0, St), #loop_frame{is=Is,cont=Cont,lvs=Lvs1,stk=Stk,env=Env} = Bf, %% Trim the new local variable stack down to original length. Lvs2 = lists:nthtail(length(Lvs0)-length(Lvs1), Lvs0), emul(Is, Cont, Lvs2, Stk, Env, Cs1, St). do_return(ArgCount , Stack , Callstack , State ) - > < emul > . do_return(Ac, Stk0, Cs0, St0) -> Find the first call frame {Ret,Stk1} = pop_vals(Ac, Stk0), %% When tracing bring the state up to date and call the tracer. Tfunc = St0#luerl.trace_func, St1 = if is_function(Tfunc) -> Tfunc(?RETURN(Ret), St0#luerl{stk=Stk1,cs=Cs1}); true -> St0 end, #call_frame{is=Is,cont=Cont,lvs=Lvs,env=Env} = Cf, emul(Is, Cont, Lvs, [Ret|Stk1], Env, Cs1, St1#luerl{cs=Cs1}). find_call_frame([#call_frame{}=Cf|Cs], _St) -> {Cf,Cs}; find_call_frame([_|Cs], St) -> find_call_frame(Cs, St). find_loop_frame([#current_line{}|Cs], St) -> %Skip current line info find_loop_frame(Cs, St); find_loop_frame([#loop_frame{}=Bf|Cs], _St) -> {Bf,Cs}; find_loop_frame(Cs, St) -> lua_error({illegal_op,break}, St#luerl{cs=Cs}). do_current_line(Instrs , Continuation , LocalVars , Stack , Env , Stack , State , %% Line, File). do_current_line(Is, Cont, Lvs, Stk, Env, Cs0, St0, Line, File) -> Push onto %% When tracing bring the state up to date and call the tracer. Tfunc = St0#luerl.trace_func, St1 = if is_function(Tfunc) -> Tfunc(?CURRENT_LINE(Line, File), St0#luerl{stk=Stk,cs=Cs1}); true -> St0 end, emul(Is, Cont, Lvs, Stk, Env, Cs1, St1). %% push_current_line(CallStack, CurrLine, FileName) -> CallStack. Push the current line info on the stack replacing an existing one %% on the top. push_current_line([#current_line{}|Cs], Line, File) -> [#current_line{line=Line,file=File}|Cs]; push_current_line(Cs, Line, File) -> [#current_line{line=Line,file=File}|Cs]. do_fcall(Instrs , LocalVars , Stack , Env , State ) - > ReturnFromEmul . %% Pop arg list and function from stack and do call. do_fcall(Is, Cont, Lvs, [Args,Func|Stk], Env, Cs, St) -> functioncall(Is, Cont, Lvs, Stk, Env, Cs, St, Func, Args). functioncall(Instrs , Cont , LocalVars , , Env , CallStack , State , Func , ) - > %% <emul> This is called from within code and continues with Instrs after call . It must move everything into State . functioncall(Is, Cont, Lvs, Stk, Env, Cs0, St, Func, Args) -> Fr = #call_frame{func=Func,args=Args,lvs=Lvs,env=Env,is=Is,cont=Cont}, Cs1 = [Fr|Cs0], call_function(Func, Args, Stk, Cs1, St). do_tail_fcall(Instrs , Cont , LocalVars , Stack , Env , State ) - > %% ReturnFromEmul. do_tail_fcall(_Is, _Cont, _Lvs, [Args,Func|_Stk], _Env, Cs, St) -> error({tail_fcall,Func,Args,Cs,St}). do_mcall(Instrs , Cont , LocalVars , Stack , Env , State , Method ) - > do_mcall(Is, Cont, Lvs, [Args,Obj|Stk], Env, Cs, St, M) -> methodcall(Is, Cont, Lvs, Stk, Env, Cs, St, Obj, M, Args). methodcall(Instrs , Cont , Var , Stk , Env , State , Object , Method , ) - > %% <emul> This is called from within code and continues with Instrs after call . It must move everything into State . methodcall(Is, Cont, Lvs, Stk, Env, Cs, St0, Obj, Meth, Args) -> %% Get the function to call from object and method. %% We must handle the metamethod and error here. io : format("mc1 ~p ~p ~p\n " , [ Obj , Meth , ] ) , case luerl_heap:get_table_key(Obj, Meth, St0) of {value,Func,St1} -> %% io:format("mc2 ~p\n", [Func]), functioncall(Is, Cont, Lvs, Stk, Env, Cs, St1, Func, [Obj|Args]); {meta,Mmeth,Margs,St1} -> io : format("mc3 ~p ~p\n " , [ Mmeth , Margs ] ) , Must first meta method to get function and then call it . %% Need to swap to get arguments for call in right order. Is1 = [?FCALL,?SINGLE,?SWAP,?FCALL|Is], emul(Is1, Cont, Lvs, [Margs,Mmeth,[Obj|Args]|Stk], Env, Cs, St1); {error,_Error,St1} -> %No method lua_error({undefined_method,Obj,Meth}, St1#luerl{stk=Stk,cs=Cs}) end. do_tail_mcall(Instrs , Cont , LocalVars , Stack , Env , State , Method ) - > %% <emul>. do_tail_mcall(_Is, _Cont, _Lvs, [Args,Obj|_Stk], _Env, Cs, St, Meth) -> error({tail_mcall,Obj,Meth,Args,Cs,St}). call_function(Function , , Stack , CallStack , State ) - > { Return , State } . %% Setup environment for function and do the actual call. call_function(#funref{env=Env}=Funref, Args, Stk, Cs, St0) -> St1 = trace_call(Funref, Args, Stk, Cs, St0), %% Here we must save the stack in state as function may need it. {Func,St2} = luerl_heap:get_funcdef(Funref, St1#luerl{stk=Stk}), call_luafunc(Func, Args, Stk, Env, Cs, St2); call_function(#erl_func{code=Func}=Funref, Args, Stk, Cs, St0) -> St1 = trace_call(Funref, Args, Stk, Cs, St0), call_erlfunc(Func, Args, Stk, Cs, St1); call_function(Func, Args, Stk, Cs, St) -> case luerl_heap:get_metamethod(Func, <<"__call">>, St) of nil -> lua_error({undefined_function,Func}, St#luerl{stk=Stk,cs=Cs}); Meta -> call_function(Meta, [Func|Args], Stk, Cs, St) end. trace_call((Function , , Stack , CallStack , State ) - > State . Trace the function call when required . trace_call(Funref, Args, _Stk, _Cs, St) -> %% When tracing bring the state up to date and call the tracer. Tfunc = St#luerl.trace_func, if is_function(Tfunc) -> Tfunc({fcall,Funref,Args}, St); true -> St end. call_luafunc(LuaFunc , , Stack , Env , CallStack , State ) - > { Return , State } . %% Make the local variable and Env frames and push them onto %% respective stacks and call the function. call_luafunc(#lua_func{lsz=Lsz,esz=Esz,pars=_Pars,body=Fis}, Args, Stk0, Env0, Cs, St0) -> L = make_loc_frame(Lsz), {Eref,St1} = make_env_frame(Esz, St0), Lvs = [L], Stk1 = [Args|Stk0], Env1 = [Eref|Env0], %% Tag = St0#luerl.tag, io : fwrite("fc : ~p\n " , [ { Lvs , Env , St0#luerl.env } ] ) , emul(Fis, [], Lvs, Stk1, Env1, Cs, St1). call_erlfunc(ErlFunc , , Stack , CallStack , State ) - > { Return , State } . %% Here we must save the stacks in state as function may need it. Note we leave the call frame to the erlang function on the call %% stack. It is popped when we return. call_erlfunc(Func, Args, Stk, Cs0, #luerl{stk=Stk0}=St0) -> case Func(Args, St0#luerl{stk=Stk,cs=Cs0}) of %% {Ret,#luerl{}=St1} when is_list(Ret) -> {Ret,St1} -> [#call_frame{is=Is,cont=Cont,lvs=Lvs,env=Env}|Cs1] = Cs0, emul(Is, Cont, Lvs, [Ret|Stk], Env, Cs1, St1#luerl{stk=Stk0,cs=Cs1}); _Other -> %% Don't include the erl_func in the call stack. lua_error(illegal_return_value, St0#luerl{stk=Stk0,cs=tl(Cs0)}) end. do_block(Instrs , LocalVars , Stack , Env , State , LocalSize , EnvSize , BlockInstrs ) - > < emul > . %% Local vars may have been updated so must continue with returned %% version. We also continue with returned stack. There should be no %% changes in the env. do_block(Is, Cont, Lvs, Stk, Env, Cs, St0, Lsz, Esz, Bis) -> L = make_loc_frame(Lsz), {Eref,St1} = make_env_frame(Esz, St0), emul(Bis, [Is|Cont], [L|Lvs], Stk, [Eref|Env], Cs, St1). do_block_open(Instrs , LocalVars , Stack , Env , State , LocalSize , EnvSize ) - > < emul > . %% Local vars may have been updated so must continue with returned %% version. We also continue with returned stack. There should be no %% changes in the env. do_block_open(Is, Cont, Lvs, Stk, Env, Cs, St0, Lsz, Esz) -> L = make_loc_frame(Lsz), {Eref,St1} = make_env_frame(Esz, St0), emul(Is, Cont, [L|Lvs], Stk, [Eref|Env], Cs, St1). do_block_close(Instrs , , Stack , Env , State , LocalSize , EnvSize ) - > < emul > . %% Pop the block local variables and environment variables. do_block_close(Is, Cont, [_|Lvs], Stk, [_|Env], Cs, St) -> emul(Is, Cont, Lvs, Stk, Env, Cs, St). make_env_frame(0, St) -> {not_used,St}; make_env_frame(Esz, St) -> { Eref , St } . make_loc_frame(0) -> not_used; make_loc_frame(Lsz) -> erlang:make_tuple(Lsz, nil). do_while(Instrs , Cont , LocalVars , Stack , Env , State , WhileEis , WhileBis ) - > %% <emul> do_while(Is, Cont, Lvs, Stk, Env, Cs0, St, Eis, Wis) -> %% Add the break frame to the call stack. Fr = #loop_frame{lvs=Lvs,stk=Stk,env=Env,is=Is,cont=Cont}, Cs1 = [Fr|Cs0], emul(Eis, [[?WHILE_LOOP(Eis, Wis)|Is]|Cont], Lvs, Stk, Env, Cs1, St). do_while_loop(Is, Cont, Lvs, [Val|Stk], Env, Cs, St, Eis, Wis) -> case boolean_value(Val) of true -> emul(Wis, [Eis,[?WHILE_LOOP(Eis, Wis)|Is]|Cont], Lvs, Stk, Env, Cs, St); false -> emul([?BREAK|Is], Cont, Lvs, Stk, Env, Cs, St) end. do_repeat(Instrs , Cont , LocalVars , Stack , Env , State , RepeatInstrs ) - > %% <emul> %% We know that at the end of the repear instructions the test value %% is calculated. do_repeat(Is, Cont, Lvs, Stk, Env, Cs0, St, Ris) -> %% Add the break frame to the call stack. Fr = #loop_frame{lvs=Lvs,stk=Stk,env=Env,is=Is,cont=Cont}, Cs1 = [Fr|Cs0], emul(Ris, [[?REPEAT_LOOP(Ris)|Is]|Cont], Lvs, Stk, Env, Cs1, St). do_repeat_loop(Is, Cont, Lvs, [Val|Stk], Env, Cs, St, Ris) -> case boolean_value(Val) of true -> emul([?BREAK|Is], Cont, Lvs, Stk, Env, Cs, St); false -> emul(Ris, [[?REPEAT_LOOP(Ris)|Is]|Cont], Lvs, Stk, Env, Cs, St) end. do_and_then(Instrs , Continuation , LocalVars , Stack , Env , State , ) - > %% <emul>. do_or_else(Instrs , Continuation , LocalVars , Stack , Env , State , ElseInstrs ) - > %% <emul>. do_and_then(Is, Cont, Lvs, [Val|Stk1]=Stk0, Env, Cs, St, Then) -> %% This is an expression and must always leave a value on stack. case boolean_value(Val) of true -> emul(Then, [Is|Cont], Lvs, Stk1, Env, Cs, St); false -> %% Non true value left on stack. emul(Is, Cont, Lvs, Stk0, Env, Cs, St) end. do_or_else(Is, Cont, Lvs, [Val|Stk1]=Stk0, Env, Cs, St, Else) -> %% This is an expression and must always leave a value on stack. case boolean_value(Val) of true -> %% Non false value left on stack. emul(Is, Cont, Lvs, Stk0, Env, Cs, St); false -> emul(Else, [Is|Cont], Lvs, Stk1, Env, Cs, St) end. do_if(Instrs , Continuation , LocalVars , Stack , Env , State , TrueInstrs ) - > %% <emul>. %% Test value on stack to choose whether to do True instructions. do_if_true(Is, Cont, Lvs, [Val|Stk], Env, Cs, St, True) -> case boolean_value(Val) of true -> emul(True, [Is|Cont], Lvs, Stk, Env, Cs, St); false -> emul(Is, Cont, Lvs, Stk, Env, Cs, St) end. do_if(Instrs , LocalVars , Stack , Env , State , TrueInstrs , FalseInstrs ) - > %% <emul>. %% Test value on stack to choose either True or False instructions. do_if(Is, Cont, Lvs0, [Val|Stk0], Env0, Cs, St0, True, False) -> case boolean_value(Val) of true -> emul(True, [Is|Cont], Lvs0, Stk0, Env0, Cs, St0); false -> emul(False, [Is|Cont], Lvs0, Stk0, Env0, Cs, St0) end. do_if(Blocks , Else , Lvs , Stk , Env , St ) - > do_if_blocks(Blocks , Else , Lvs , Stk , Env , St ) . do_if_blocks([{T , B}|Ts ] , Else , Lvs0 , Stk0 , Env0 , St0 ) - > { Lvs1,[Val|Stk1],Env1,St1 } = emul(T , Lvs0 , Stk0 , Env0 , St0 ) , %% case boolean_value(Val) of true - > emul(B , Lvs1 , Stk1 , Env1 , St1 ) ; false - > do_if_blocks(Ts , Lvs1 , Stk1 , Env1 , St1 ) %% end; %% do_if_blocks([], Else, Lvs, Stk, Env, St) -> %% emul(Else, Lvs, Stk, Env, St). do_if_block([?BLOCK(Lsz , Esz , ) ] , Lvs0 , Stk0 , Env0 , St0 , Is ) - > { Lvs1,Stk1,Env1,St1 } = do_block(Bis , Lvs0 , Stk0 , Env0 , St0 , Lsz , Esz ) , emul(Is , Lvs1 , Stk1 , Env1 , St1 ) ; do_if_block(Bis , Lvs0 , Stk0 , Env0 , St0 , Is ) - > { Lvs1,Stk1,Env1,St1 } = emul(Bis , Lvs0 , Stk0 , Env0 , St0 ) , emul(Is , Lvs1 , Stk1 , Env1 , St1 ) . do_numfor(Instrs , LocalVars , Stack , Env , State , Varname , FromInstrs ) - > %% <emul> do_numfor(Is, Cont, Lvs, [Step,Limit,Init|Stk], Env, Cs0, St, _, Fis) -> First check if we have numbers . case luerl_lib:args_to_numbers([Init,Limit,Step]) of [I,L,S] -> %% Add the break frame to the call stack. Fr = #loop_frame{lvs=Lvs,stk=Stk,env=Env,is=Is,cont=Cont}, Cs1 = [Fr|Cs0], do_numfor_loop(Is, Cont, Lvs, Stk, Env, Cs1, St, I, L, S, Fis); error -> badarg_error(loop, [Init,Limit,Step], St#luerl{cs=Cs0}) end. do_numfor_loop(Is, Cont, Lvs, Stk, Env, Cs, St, N, Limit, Step, Fis) -> %% itrace_print("nl: ~p\n", [{N,Stk}]), %% Leave the current counter at the top of the stack for code to get. if Step > 0, N =< Limit -> %Keep going emul(Fis, [[?NFOR_LOOP(N+Step, Limit, Step, Fis)|Is]|Cont], Lvs, [N|Stk], Env, Cs, St); Step < 0, N >= Limit -> %Keep going emul(Fis, [[?NFOR_LOOP(N+Step, Limit, Step, Fis)|Is]|Cont], Lvs, [N|Stk], Env, Cs, St); true -> %Done! emul([?BREAK|Is], Cont, Lvs, Stk, Env, Cs, St) end. do_genfor(Instrs , LocalVars , Stack , Env , CallStack , State , Vars , FromInstrs ) - > < emul > %% The top of the stack will contain the return values from the explist. do_genfor(Is, Cont, Lvs, [Val|Stk], Env, Cs0, St, _, Fis) -> Sneaky , export Func , Data , Var [Func] -> Data = nil, Var = nil; [Func,Data] -> Var = nil; [Func,Data,Var|_] -> ok; Func -> Data = nil, Var = nil end, %% Add the break frame to the call stack. Fr = #loop_frame{lvs=Lvs,stk=Stk,env=Env,is=Is,cont=Cont}, Cs1 = [Fr|Cs0], do_genfor_call(Is, Cont, Lvs, Stk, Env, Cs1, St, Func, Data, Var, Fis). do_genfor_call(Is, Cont, Lvs, Stk, Env, Cs, St, Func, Data, Val, Fis) -> emul([?FCALL,?GFOR_LOOP(Func, Data, Fis)|Is], Cont, Lvs, [[Data,Val],Func|Stk], Env, Cs, St). do_genfor_loop(Is, Cont, Lvs, [Vals|Stk], Env, Cs, St, Func, Data, Fis) -> case boolean_value(Vals) of true -> emul(Fis, [[?GFOR_CALL(Func,Data,hd(Vals),Fis)|Is]|Cont], Lvs, [Vals|Stk], Env, Cs, St); false -> emul([?BREAK|Is], Cont, Lvs, Stk, Env, Cs, St) end. build_tab(FieldCount , Index , Stack , State ) - > { TableRef , Stack , State } . FieldCount is how many Key / Value pairs are on the stack , Index is the index of the next value in the acc . build_tab(Fc, I, [Last|Stk0], St0) -> Fs0 = build_tab_last(I, Last), {Fs1,Stk1} = build_tab_loop(Fc, Stk0, Fs0), io : : ~p\n " , [ { Fc , I , Acc , Fs0,Fs1 } ] ) , {Tref,St1} = luerl_heap:alloc_table(Fs1, St0), {Tref,Stk1,St1}. build_tab_last(I, [V|Vs]) -> [{I,V}|build_tab_last(I+1, Vs)]; build_tab_last(_, []) -> []; build_tab_last(_, Last) -> error({boom,build_tab_acc,Last}). build_tab_loop(0, Stk, Fs) -> {Fs,Stk}; build_tab_loop(C, [V,K|Stk], Fs) -> build_tab_loop(C-1, Stk, [{K,V}|Fs]). op(Op , Arg , State ) - > OpReturn . op(Op , Arg1 , , State ) - > OpReturn . %% = { value , Ret , State } | { meta , Method , , State } | %% {error,Error,State}. %% %% The built-in operators. Always return a single value! op('-', A, St) -> numeric_op('-', A, St, <<"__unm">>, fun (N) -> -N end); op('not', A, St) -> {value,not ?IS_TRUE(A),St}; op('~', A, St) -> integer_op('~', A, St, <<"__bnot">>, fun (N) -> bnot(N) end); op('#', A, St) -> length_op('#', A, St); op(Op, A, St) -> {error,{badarg,Op,[A]},St}. %% Numeric operators. op('+', A1, A2, St) -> numeric_op('+', A1, A2, St, <<"__add">>, fun (N1,N2) -> N1+N2 end); op('-', A1, A2, St) -> numeric_op('-', A1, A2, St, <<"__sub">>, fun (N1,N2) -> N1-N2 end); op('*', A1, A2, St) -> numeric_op('*', A1, A2, St, <<"__mul">>, fun (N1,N2) -> N1*N2 end); op('/', A1, A2, St) -> numeric_op('/', A1, A2, St, <<"__div">>, fun (N1,N2) -> N1/N2 end); The ' // ' and ' % ' operators are specially handled to avoid first %% converting integers to floats and potentially lose precision. op('//', A1, A2, St) -> numeric_op('//', A1, A2, St, <<"__idiv">>, fun (N1,N2) when is_integer(N1), is_integer(N2) -> Idiv = N1 div N2, Irem = N1 rem N2, if Irem =:= 0 -> Idiv; Idiv < 0 -> Idiv - 1; true -> Idiv end; (N1,N2) -> 0.0 + floor(N1/N2) end); op('%', A1, A2, St) -> numeric_op('%', A1, A2, St, <<"__mod">>, fun (N1,N2) when is_integer(N1), is_integer(N2) -> Irem = N1 rem N2, if (Irem < 0) and (N2 >= 0) -> Irem + N2; (Irem > 0) and (N2 < 0) -> Irem + N2; true -> Irem end; if < 0 - > %% if N2 < 0 -> Irem; %% true -> Irem + N2 %% end; > 0 - > %% if N2 < 0 -> Irem + N2; %% true -> Irem %% end; true - > 0 % = : = 0 %% end; (N1,N2) -> N1 - floor(N1/N2)*N2 end); op('^', A1, A2, St) -> numeric_op('^', A1, A2, St, <<"__pow">>, fun (N1,N2) -> math:pow(N1, N2) end); Bitwise operators . %% The '>>' is an arithmetic shift as a logical shift implies a word %% size which we don't have. op('&', A1, A2, St) -> integer_op('&', A1, A2, St, <<"__band">>, fun (N1,N2) -> N1 band N2 end); op('|', A1, A2, St) -> integer_op('|', A1, A2, St, <<"__bor">>, fun (N1,N2) -> N1 bor N2 end); op('~', A1, A2, St) -> integer_op('~', A1, A2, St, <<"__bxor">>, fun (N1,N2) -> N1 bxor N2 end); op('<<', A1, A2, St) -> integer_op('<<', A1, A2, St, <<"__shl">>, fun (N1,N2) -> N1 bsl N2 end); op('>>', A1, A2, St) -> integer_op('>>', A1, A2, St, <<"__shr">>, fun (N1,N2) -> N1 bsr N2 end); %% Relational operators, getting close. op('==', A1, A2, St) -> eq_op('==', A1, A2, St); op('~=', A1, A2, St) -> neq_op('~=', A1, A2, St); op('<=', A1, A2, St) -> le_op('<=', A1, A2, St); op('>=', A1, A2, St) -> le_op('>=', A2, A1, St); op('<', A1, A2, St) -> lt_op('<', A1, A2, St); op('>', A1, A2, St) -> lt_op('>', A2, A1, St); %% String operator. op('..', A1, A2, St) -> concat_op(A1, A2, St); %% Bad args here. op(Op, A1, A2, St) -> {error,{badarg,Op,[A1,A2]}, St}. -ifndef(HAS_FLOOR). %% floor(Number) -> integer(). Floor does not exist before 20 so we need to do it ourselves . floor(N) when is_integer(N) -> N; floor(N) when is_float(N) -> round(N - 0.5). -endif. %% length_op(Op, Arg, State) -> OpReturn. numeric_op(Op , Arg , State , Event , Raw ) - > OpReturn . numeric_op(Op , Arg , Arg , State , Event , Raw ) - > OpReturn . %% integer_op(Op, Arg, State, Event, Raw) -> OpReturn. %% integer_op(Op, Arg, Arg, State, Event, Raw) -> OpReturn. %% eq_op(Op, Arg, Arg, State) -> OpReturn. %% neq_op(Op, Arg, Arg, State) -> OpReturn. %% lt_op(Op, Arg, Arg, State) -> OpReturn. %% le_op(Op, Arg, Arg, State) -> OpReturn. %% concat_op(Arg, Arg, State) -> OpReturn. %% = { value , Ret , State } | { meta , Method , , State } | %% {error,Error,State}. %% %% Together with their metas straight out of the reference %% manual. Note that: %% - numeric_op string args are always floats %% - eq/neq metamethods here must return boolean values and the tests %% themselves are type dependent length_op(_Op, A, St) when is_binary(A) -> {value,byte_size(A),St}; length_op(_Op, A, St) -> case luerl_heap:get_metamethod(A, <<"__len">>, St) of nil -> if ?IS_TREF(A) -> {value,luerl_lib_table:raw_length(A, St),St}; true -> {error,{badarg,'#',[A]}, St} end; Meth -> {meta,Meth,[A],St} end. numeric_op(Op, A, St, E, Raw) -> case luerl_lib:arg_to_number(A) of error -> op_meta(Op, A, E, St); N -> {value,Raw(N),St} end. numeric_op(Op, A1, A2, St, E, Raw) -> case luerl_lib:args_to_numbers(A1, A2) of [N1,N2] -> {value,Raw(N1, N2),St}; error -> op_meta(Op, A1, A2, E, St) end. integer_op(Op, A, St, E, Raw) -> case luerl_lib:arg_to_integer(A) of error -> op_meta(Op, A, E, St); N -> {value,Raw(N),St} end. integer_op(Op, A1, A2, St, E, Raw) -> case luerl_lib:args_to_integers(A1, A2) of [N1,N2] -> {value,Raw(N1, N2),St}; error -> op_meta(Op, A1, A2, E, St) end. eq_op(_Op, A1, A2, St) when A1 == A2 -> {value,true,St}; eq_op(_Op, A1, A2, St) when ?IS_TREF(A1), ?IS_TREF(A2) ; ?IS_USDREF(A1), ?IS_USDREF(A2) -> case get_eqmetamethod(A1, A2, St) of nil -> {value,false,St}; Meth -> Func = fun (Args, St0) -> {Ret,St1} = functioncall(Meth, Args, St0), {[boolean_value(Ret)],St1} end, {meta,#erl_func{code=Func},[A1,A2],St} end; eq_op(_, _, _, St) -> {value,false,St}. neq_op(_Op, A1, A2, St) when A1 == A2 -> {value,false,St}; neq_op(_Op, A1, A2, St) when ?IS_TREF(A1), ?IS_TREF(A2) ; ?IS_USDREF(A1), ?IS_USDREF(A2) -> case get_eqmetamethod(A1, A2, St) of nil -> {value,true,St}; Meth -> Func = fun (Args, St0) -> {Ret,St1} = functioncall(Meth, Args, St0), {[not boolean_value(Ret)],St1} end, {meta,#erl_func{code=Func},[A1,A2],St} end; neq_op(_, _, _, St) -> {value,true,St}. get_eqmetamethod(A1, A2, St) -> %% Must have "same" metamethod here. How do we test? case luerl_heap:get_metamethod(A1, <<"__eq">>, St) of nil -> nil; Meth -> case luerl_heap:get_metamethod(A2, <<"__eq">>, St) of Meth -> Meth; %Must be the same method _ -> nil end end. lt_op(_Op, A1, A2, St) when is_number(A1), is_number(A2) -> {value,A1 < A2,St}; lt_op(_Op, A1, A2, St) when is_binary(A1), is_binary(A2) -> {value,A1 < A2,St}; lt_op(Op, A1, A2, St) -> op_meta(Op, A1, A2, <<"__lt">>, St). le_op(_Op, A1, A2, St) when is_number(A1), is_number(A2) -> {value,A1 =< A2,St}; le_op(_Op, A1, A2, St) when is_binary(A1), is_binary(A2) -> {value,A1 =< A2,St}; le_op(Op, A1, A2, St) -> Must check for first _ _ le then _ _ lt metamethods . case luerl_heap:get_metamethod(A1, A2, <<"__le">>, St) of nil -> %% Try for not (Op2 < Op1) instead. case luerl_heap:get_metamethod(A1, A2, <<"__lt">>, St) of nil -> {error,{badarg,Op,[A1,A2]}, St}; Meth -> {meta,Meth,[A2,A1],St} end; Meth -> {meta,Meth,[A1,A2],St} end. concat_op(A1, A2, St) -> case luerl_lib:conv_list([A1,A2], [lua_string,lua_string]) of [S1,S2] -> {value,<<S1/binary,S2/binary>>,St}; error -> op_meta('..', A1, A2, <<"__concat">>, St) end. op_meta(Op, A, E, St) -> case luerl_heap:get_metamethod(A, E, St) of nil -> {error,{badarg,Op,[A]}, St}; Meth -> {meta,Meth,[A],St} end. op_meta(Op, A1, A2, E, St) -> case luerl_heap:get_metamethod(A1, A2, E, St) of nil -> {error,{badarg,Op,[A1,A2]},St}; Meth -> {meta,Meth,[A1,A2],St} end. %% boolean_value(Rets) -> boolean(). %% Return the "boolean" value of a value/function return list. boolean_value([nil|_]) -> false; boolean_value([false|_]) -> false; boolean_value([_|_]) -> true; boolean_value([]) -> false; boolean_value(nil) -> false; boolean_value(false) -> false; boolean_value(_) -> true. %% first_value(Rets) -> Value. %% multiple_value(Value) -> [Value]. first_value([V|_]) -> V; first_value([]) -> nil. multiple_value(V) when not is_list(V) -> [V].
null
https://raw.githubusercontent.com/rvirding/luerl/5e61c1838d08430af67fb870995b05a41d64aeee/src/luerl_emul.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. File : luerl_emul.erl local/global variables. not try to fold similar structures into common code. While this means we get more code it also becomes more explicit and clear what we are doing. It may also allow for specific optimisations. And example is that we DON'T fold 'var' and 'funcname' even though they are almost the same. Issues: how should we handle '...'? Now we treat it as any (local) variable. Basic interface. Temporary shadow calls. For testing. -compile(inline). %For when we are optimising -compile({inline,[boolean_value/1,first_value/1]}). -define(ITRACE_DO(Expr), ok). Temporary shadow calls. init() -> State. Allocate the _G table and initialise the environment Global environment Add the other standard libraries. Set _G variable to point to it and add it to packages.loaded. Add key to global and to package.loaded. Access elements in the global name table, _G. Search down tables which stops when no more tables. Setter down tables. Access tables, as opposed to the environment (which are also tables). Setting a value to 'nil' will clear it from the array but not from the table; however, we won't add a nil value. NOTE: WE ALWAYS RETURN A SINGLE VALUE! get_local_var(Depth, Index, Frames) -> Val. We must have the state as the environments are global in the state. io:format("******** SEV DONE ~w ~w ********\n", [D,I]), io:format("******** GEV DONE ~w ~w ********\n", [D, I]), load_chunk(FunctionDefCode, Env, State) -> {Function,State}. Load a chunk from the compiler which is a compiled function definition whose instructions define everything. Return a callable state. load_chunk_i(Instr, FuncRefs, Status) -> {Instr,FuncRefs,State}. Load chunk instructions. We keep track of the functions refs and save the ones directly accessed in each function. This will make gc easier as we will not have to step through the function code at gc time. We include the dymanmic instructions here even though the compiler does not generate them. This should make us more future proof. This is dynamic This is dynamic This is dynamic This is dynamic Then the rest which we don't have to worry about. These ares called from the outside and expect everything necessary to be in the state. Lua function Reset the stacks Get the function to call from object and method. No method The cost of checking the itrace process variable is very slight compared to everythin else. The faster (yeah sure) version. emul(Is, Cont, Lvs, Stk, Env, Cs, St) -> emul_1(Is, Cont, Lvs, Stk, Env, Cs, St). The tracing versions. Expression instructions. We must handle the metamethod and error here. We must handle the metamethod and error here. We must handle the metamethod and error here. [?PUSH_LIT(Key),?GET_KEY] [?PUSH_LIT(Key),?SET_KEY] Update the env field of the function reference with the current environment. Control instructions. Pop Vc vals off the stack, put in a list and push onto the stack. Pop argument list off the stack and push args onto the stack. Pop Ac args off the stack, put in a list and push onto the stack. This just a comment which is ignored. Pop Count values off the stack and push onto the value list. This a list tail deepest. Fill with 'nil' if not enough values. Drop the rest ReturnFromEmul. ReturnFromEmul. We must handle the metamethod and error here. We must handle the metamethod and error here. We must handle the metamethod and error here. We must handle the metamethod and error here. Trim the new local variable stack down to original length. When tracing bring the state up to date and call the tracer. Skip current line info Line, File). When tracing bring the state up to date and call the tracer. push_current_line(CallStack, CurrLine, FileName) -> CallStack. on the top. Pop arg list and function from stack and do call. <emul> ReturnFromEmul. <emul> Get the function to call from object and method. We must handle the metamethod and error here. io:format("mc2 ~p\n", [Func]), Need to swap to get arguments for call in right order. No method <emul>. Setup environment for function and do the actual call. Here we must save the stack in state as function may need it. When tracing bring the state up to date and call the tracer. Make the local variable and Env frames and push them onto respective stacks and call the function. Tag = St0#luerl.tag, Here we must save the stacks in state as function may need it. stack. It is popped when we return. {Ret,#luerl{}=St1} when is_list(Ret) -> Don't include the erl_func in the call stack. Local vars may have been updated so must continue with returned version. We also continue with returned stack. There should be no changes in the env. Local vars may have been updated so must continue with returned version. We also continue with returned stack. There should be no changes in the env. Pop the block local variables and environment variables. <emul> Add the break frame to the call stack. <emul> We know that at the end of the repear instructions the test value is calculated. Add the break frame to the call stack. <emul>. <emul>. This is an expression and must always leave a value on stack. Non true value left on stack. This is an expression and must always leave a value on stack. Non false value left on stack. <emul>. Test value on stack to choose whether to do True instructions. <emul>. Test value on stack to choose either True or False instructions. case boolean_value(Val) of end; do_if_blocks([], Else, Lvs, Stk, Env, St) -> emul(Else, Lvs, Stk, Env, St). <emul> Add the break frame to the call stack. itrace_print("nl: ~p\n", [{N,Stk}]), Leave the current counter at the top of the stack for code to get. Keep going Keep going Done! The top of the stack will contain the return values from the explist. Add the break frame to the call stack. {error,Error,State}. The built-in operators. Always return a single value! Numeric operators. ' operators are specially handled to avoid first converting integers to floats and potentially lose precision. ', A1, A2, St) -> ', A1, A2, St, <<"__mod">>, if N2 < 0 -> Irem; true -> Irem + N2 end; if N2 < 0 -> Irem + N2; true -> Irem end; = : = 0 end; The '>>' is an arithmetic shift as a logical shift implies a word size which we don't have. Relational operators, getting close. String operator. Bad args here. floor(Number) -> integer(). length_op(Op, Arg, State) -> OpReturn. integer_op(Op, Arg, State, Event, Raw) -> OpReturn. integer_op(Op, Arg, Arg, State, Event, Raw) -> OpReturn. eq_op(Op, Arg, Arg, State) -> OpReturn. neq_op(Op, Arg, Arg, State) -> OpReturn. lt_op(Op, Arg, Arg, State) -> OpReturn. le_op(Op, Arg, Arg, State) -> OpReturn. concat_op(Arg, Arg, State) -> OpReturn. {error,Error,State}. Together with their metas straight out of the reference manual. Note that: - numeric_op string args are always floats - eq/neq metamethods here must return boolean values and the tests themselves are type dependent Must have "same" metamethod here. How do we test? Must be the same method Try for not (Op2 < Op1) instead. boolean_value(Rets) -> boolean(). Return the "boolean" value of a value/function return list. first_value(Rets) -> Value. multiple_value(Value) -> [Value].
Copyright ( c ) 2013 - 2020 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , Author : Purpose : A basic LUA 5.3 machine emulator . First version of emulator . Compiler so far only explicitly handles We explicitly mirror the parser rules which generate the AST and do -module(luerl_emul). -include("luerl.hrl"). -include("luerl_comp.hrl"). -include("luerl_instrs.hrl"). -export([init/0,gc/1]). -export([call/2,call/3,emul/2]). -export([load_chunk/2,load_chunk/3]). -export([functioncall/3,methodcall/4, set_global_key/3,get_global_key/2, get_table_keys/2,get_table_keys/3, set_table_keys/3,set_table_keys/4, get_table_key/3,set_table_key/4 ]). -export([alloc_table/2,set_userdata/3,get_metamethod/3]). -export([pop_vals/2,push_vals/3]). -import(luerl_lib, [lua_error/2,badarg_error/3]). -define(ITRACE_DO(Expr), begin (get(luerl_itrace) /= undefined) andalso Expr end). gc(St) -> luerl_heap:gc(St). alloc_table(Itab, St) -> luerl_heap:alloc_table(Itab, St). set_userdata(Ref, Data, St) -> luerl_heap:set_userdata(Ref, Data, St). get_metamethod(Obj, Event, St) -> luerl_heap:get_metamethod(Obj, Event, St). Initialise the basic state . init() -> St1 = luerl_heap:init(), St3 = St2#luerl{g=_G}, Now we can start adding libraries . Package MUST be first ! St4 = load_lib(<<"package">>, luerl_lib_package, St3), St5 = load_libs([ {<<"bit32">>,luerl_lib_bit32}, {<<"io">>,luerl_lib_io}, {<<"math">>,luerl_lib_math}, {<<"os">>,luerl_lib_os}, {<<"string">>,luerl_lib_string}, {<<"utf8">>,luerl_lib_utf8}, {<<"table">>,luerl_lib_table}, {<<"debug">>,luerl_lib_debug} ], St4), St6 = set_global_key(<<"_G">>, _G, St5), set_table_keys([<<"package">>,<<"loaded">>,<<"_G">>], _G, St6). load_libs(Libs, St) -> Fun = fun ({Key,Mod}, S) -> load_lib(Key, Mod, S) end, lists:foldl(Fun, St, Libs). load_lib(Key , Module , State ) - > State . load_lib(Key, Mod, St0) -> {Tab,St1} = Mod:install(St0), St2 = set_global_key(Key, Tab, St1), set_table_keys([<<"package">>,<<"loaded">>,Key], Tab, St2). set_global_key(Key , Value , State ) - > State . get_global_key(Key , State ) - > { [ Val],State } . set_global_key(Key, Val, #luerl{g=G}=St) -> set_table_key(G, Key, Val, St). get_global_key(Key, #luerl{g=G}=St) -> get_table_key(G, Key, St). get_table_keys(Keys , State ) - > { Value , State } . get_table_keys(Tab , Keys , State ) - > { Value , State } . get_table_keys(Keys, St) -> get_table_keys(St#luerl.g, Keys, St). get_table_keys(Tab, [K|Ks], St0) -> {Val,St1} = get_table_key(Tab, K, St0), get_table_keys(Val, Ks, St1); get_table_keys(Val, [], St) -> {Val,St}. set_table_keys(Keys , , State ) - > State . set_table_keys(Tab , Keys , , State ) - > State . set_table_keys(Keys, Val, St) -> set_table_keys(St#luerl.g, Keys, Val, St). set_table_keys(Tab, [K], Val, St) -> set_table_key(Tab, K, Val, St); set_table_keys(Tab0, [K|Ks], Val, St0) -> {Tab1,St1} = get_table_key(Tab0, K, St0), set_table_keys(Tab1, Ks, Val, St1). set_table_key(Tref , Key , Value , State ) - > State . get_table_key(Tref , Key , State ) - > { Val , State } . set_table_key(Tref, Key, Val, St0) -> case luerl_heap:set_table_key(Tref, Key, Val, St0) of {value,_Val,St1} -> St1; {meta,Meth,Args,St1} -> {_Ret,St2} = functioncall(Meth, Args, St1), St2; {error,Error,St1} -> lua_error(Error, St1) end. get_table_key(Tref, Key, St0) -> case luerl_heap:get_table_key(Tref, Key, St0) of {value,Val,St1} -> {Val,St1}; {meta,Meth,Args,St1} -> {Ret,St2} = functioncall(Meth, Args, St1), {first_value(Ret),St2}; {error,Error,St1} -> lua_error(Error, St1) end. set_local_var(Depth , Index , Var , Frames ) - > Frames . set_local_var(1, I, V, [F|Fs]) -> [setelement(I, F, V)|Fs]; set_local_var(D, I, V, [F|Fs]) -> [F|set_local_var(D-1, I, V, Fs)]. get_local_var(1, I, [F|_]) -> element(I, F); get_local_var(D, I, [_|Fs]) -> get_local_var(D-1, I, Fs). set_env_var(Depth , Index , , EnvStack , State ) - > State . get_env_var(Depth , Index , EnvStack , State ) - > Val . set_env_var(D, I, Val, Estk, St) -> St1 = set_env_var_1(D, I, Val, Estk, St), St1. set_env_var_1(1, I, Val, [Eref|_], St) -> luerl_heap:set_env_var(Eref, I, Val, St); set_env_var_1(2, I, Val, [_,Eref|_], St) -> luerl_heap:set_env_var(Eref, I, Val, St); set_env_var_1(D, I, Val, Env, St) -> luerl_heap:set_env_var(lists:nth(D, Env), I, Val, St). get_env_var(D, I, Env, St) -> Val = get_env_var_1(D, I, Env, St), Val. get_env_var_1(1, I, [Eref|_], St) -> luerl_heap:get_env_var(Eref, I, St); get_env_var_1(2, I, [_,Eref|_], St) -> luerl_heap:get_env_var(Eref, I, St); get_env_var_1(D, I, Env, St) -> luerl_heap:get_env_var(lists:nth(D, Env), I, St). load_chunk(FunctionDefCode , State ) - > { Function , State } . function reference which defines everything and a updated Luerl load_chunk(Code, St) -> load_chunk(Code, [], St). load_chunk([Code], [], St0) -> {?PUSH_FDEF(Funref),_,St1} = load_chunk_i(Code, [], St0), {Funref,St1}. load_chunk_is(Instrs , FuncRefs , Status ) - > { Instrs , FuncRefs , State } . load_chunk_is([I0|Is0], Funrs0, St0) -> {I1,Funrs1,St1} = load_chunk_i(I0, Funrs0, St0), {Is1,Funrs2,St2} = load_chunk_is(Is0, Funrs1, St1), {[I1|Is1],Funrs2,St2}; load_chunk_is([], Funrs, St) -> {[],Funrs,St}. First the instructions with nested code . load_chunk_i(?PUSH_FDEF(Anno, Lsz, Esz, Pars, B0), Funrs0, St0) -> {B1,Funrs,St1} = load_chunk_is(B0, [], St0), Fdef = #lua_func{anno=Anno,funrefs=Funrs,lsz=Lsz,esz=Esz,pars=Pars,body=B1}, {Funref,St2} = luerl_heap:alloc_funcdef(Fdef, St1), Funrs1 = ordsets:add_element(Funref, Funrs0), {?PUSH_FDEF(Funref),Funrs1,St2}; load_chunk_i(?BLOCK(Lsz, Esz, B0), Funrs0, St0) -> {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?BLOCK(Lsz, Esz, B1),Funrs1,St1}; load_chunk_i(?REPEAT(B0), Funrs0, St0) -> {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?REPEAT(B1),Funrs1,St1}; {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?REPEAT_LOOP(B1),Funrs1,St1}; load_chunk_i(?WHILE(E0, B0), Funrs0, St0) -> {E1,Funrs1,St1} = load_chunk_is(E0, Funrs0, St0), {B1,Funrs2,St2} = load_chunk_is(B0, Funrs1, St1), {?WHILE(E1, B1),Funrs2,St2}; load_chunk_i(?WHILE_LOOP(E0, B0), Funrs0, St0) -> {E1,Funrs1,St1} = load_chunk_is(E0, Funrs0, St0), {B1,Funrs2,St2} = load_chunk_is(B0, Funrs1, St1), {?WHILE_LOOP(E1, B1),Funrs2,St2}; load_chunk_i(?AND_THEN(T0), Funrs0, St0) -> {T1,Funrs1,St1} = load_chunk_is(T0, Funrs0, St0), {?AND_THEN(T1),Funrs1,St1}; load_chunk_i(?OR_ELSE(T0), Funrs0, St0) -> {T1,Funrs1,St1} = load_chunk_is(T0, Funrs0, St0), {?OR_ELSE(T1),Funrs1,St1}; load_chunk_i(?IF_TRUE(T0), Funrs0, St0) -> {T1,Funrs1,St1} = load_chunk_is(T0, Funrs0, St0), {?IF_TRUE(T1),Funrs1,St1}; load_chunk_i(?IF(T0, F0), Funrs0, St0) -> {T1,Funrs1,St1} = load_chunk_is(T0, Funrs0, St0), {F1,Funrs2,St2} = load_chunk_is(F0, Funrs1, St1), {?IF(T1, F1),Funrs2,St2}; load_chunk_i(?NFOR(V, B0), Funrs0, St0) -> {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?NFOR(V, B1),Funrs1,St1}; {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?NFOR_LOOP(N, L, S, B1),Funrs1,St1}; load_chunk_i(?GFOR(Vs, B0), Funrs0, St0) -> {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?GFOR(Vs, B1),Funrs1,St1}; {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?GFOR_CALL(F, D, V, B1),Funrs1,St1}; {B1,Funrs1,St1} = load_chunk_is(B0, Funrs0, St0), {?GFOR_LOOP(F, D, B1),Funrs1,St1}; load_chunk_i(I, Funrs, St) -> {I,Funrs,St}. call(Function , State ) - > { Return , State } . call(Function , , State ) - > { Return , State } . functioncall(Function , , State ) - > { Return , State } . methodcall(Object , Method , , State ) - > { Return , State } . call(Func, St) -> call(Func, [], St). {Ret,St1} = functioncall(Funref, Args, St0), Should do GC here . {Ret,St1}; Erlang function {Ret,St1} = functioncall(Func, Args, St0), Should do GC here . {Ret,St1}. functioncall(Func, Args, #luerl{stk=Stk}=St0) -> Fr = #call_frame{func=Func,args=Args,lvs=[],env=[],is=[],cont=[]}, Cs0 = [Fr], {_Lvs,[Ret|_],_Env,Cs1,St1} = call_function(Func, Args, Stk, Cs0, St0), methodcall(Obj, Meth, Args, St0) -> case get_table_key(Obj, Meth, St0) of lua_error({undefined_method,Obj,Meth}, St1); {Func,St1} -> functioncall(Func, [Obj|Args], St1) end. emul(Instrs , State ) . emul(Instrs , Continuation , LocalVariables , Stack , Env , CallStack , State ) . emul(Is, St) -> emul(Is, [], {}, [], [], [], St). emul([I|_]=Is, Cont, Lvs, Stk, Env, Cs, St) -> ?ITRACE_DO(begin io:fwrite("Is: ~p\n", [Is]), io:fwrite("Cnt: ~p\n", [Cont]), io:fwrite("Lvs: ~p\n", [Lvs]), io:fwrite("Env: ~p\n", [Env]), io:fwrite("Stk: ~p\n", [Stk]), io:fwrite("Cs: ~p\n", [Cs]), io:fwrite("I: ~p\n", [I]), io:put_chars("--------\n") end), emul_1(Is, Cont, Lvs, Stk, Env, Cs, St); emul([], Cont, Lvs, Stk, Env, Cs, St) -> ?ITRACE_DO(begin io:fwrite("Is: ~p\n", [[]]), io:fwrite("Cnt: ~p\n", [Cont]), io:fwrite("Lvs: ~p\n", [Lvs]), io:fwrite("Env: ~p\n", [Env]), io:fwrite("Stk: ~p\n", [Stk]), io:fwrite("Cs: ~p\n", [Cs]), io:put_chars("--------\n") end), emul_1([], Cont, Lvs, Stk, Env, Cs, St). itrace_print(Format , ) - > ? ITRACE_DO(io : fwrite(Format , ) ) . emul_1([?PUSH_LIT(L)|Is], Cont, Lvs, Stk, Env, Cs, St) -> emul(Is, Cont, Lvs, [L|Stk], Env, Cs, St); emul_1([?PUSH_LVAR(D, I)|Is], Cont, Lvs, Stk, Env, Cs, St) -> Val = get_local_var(D, I, Lvs), emul(Is, Cont, Lvs, [Val|Stk], Env, Cs, St); emul_1([?PUSH_EVAR(D, I)|Is], Cont, Lvs, Stk, Env, Cs, St) -> Val = get_env_var(D, I, Env, St), emul(Is, Cont, Lvs, [Val|Stk], Env, Cs, St); emul_1([?PUSH_GVAR(Key)|Is], Cont, Lvs, Stk, Env, Cs, St0) -> case luerl_heap:get_global_key(Key, St0) of {value,Val,St1} -> emul(Is, Cont, Lvs, [Val|Stk], Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL,?SINGLE|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end; emul_1([?PUSH_LAST_LIT(L)|Is], Cont, Lvs, Stk, Env, Cs, St) -> emul(Is, Cont, Lvs, [[L]|Stk], Env, Cs, St); emul_1([?PUSH_LAST_LVAR(D, I)|Is], Cont, Lvs, Stk, Env, Cs, St) -> Val = get_local_var(D, I, Lvs), emul(Is, Cont, Lvs, [[Val]|Stk], Env, Cs, St); emul_1([?PUSH_LAST_EVAR(D, I)|Is], Cont, Lvs, Stk, Env, Cs, St) -> Val = get_env_var(D, I, Env, St), emul(Is, Cont, Lvs, [[Val]|Stk], Env, Cs, St); emul_1([?PUSH_LAST_GVAR(Key)|Is], Cont, Lvs, Stk, Env, Cs, St0) -> case luerl_heap:get_global_key(Key, St0) of {value,Val,St1} -> emul(Is, Cont, Lvs, [[Val]|Stk], Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end; emul_1([?STORE_LVAR(D, I)|Is], Cont, Lvs0, [Val|Stk], Env, Cs, St) -> Lvs1 = set_local_var(D, I, Val, Lvs0), emul(Is, Cont, Lvs1, Stk, Env, Cs, St); emul_1([?STORE_EVAR(D, I)|Is], Cont, Lvs, [Val|Stk], Env, Cs, St0) -> St1 = set_env_var(D, I, Val, Env, St0), emul(Is, Cont, Lvs, Stk, Env, Cs, St1); emul_1([?STORE_GVAR(Key)|Is], Cont, Lvs, [Val|Stk], Env, Cs, St0) -> case luerl_heap:set_global_key(Key, Val, St0) of {value,_,St1} -> emul(Is, Cont, Lvs, Stk, Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL,?POP|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end; emul_1([?GET_KEY|Is], Cont, Lvs, [Key,Tab|Stk], Env, Cs, St) -> do_get_key(Is, Cont, Lvs, Stk, Env, Cs, St, Tab, Key); emul_1([?GET_LIT_KEY(Key)|Is], Cont, Lvs, [Tab|Stk], Env, Cs, St) -> do_get_key(Is, Cont, Lvs, Stk, Env, Cs, St, Tab, Key); emul_1([?SET_KEY|Is], Cont, Lvs, [Key,Tab,Val|Stk], Env, Cs, St) -> do_set_key(Is, Cont, Lvs, Stk, Env, Cs, St, Tab, Key, Val); emul_1([?SET_LIT_KEY(Key)|Is], Cont, Lvs, [Tab,Val|Stk], Env, Cs, St) -> do_set_key(Is, Cont, Lvs, Stk, Env, Cs, St, Tab, Key, Val); emul_1([?SINGLE|Is], Cont, Lvs, [Val|Stk], Env, Cs, St) -> emul(Is, Cont, Lvs, [first_value(Val)|Stk], Env, Cs, St); emul_1([?MULTIPLE|Is], Cont, Lvs, [Val|Stk], Env, Cs, St) -> emul(Is, Cont, Lvs, [multiple_value(Val)|Stk], Env, Cs, St); emul_1([?BUILD_TAB(Fc, I)|Is], Cont, Lvs, Stk0, Env, Cs, St0) -> {Tab,Stk1,St1} = build_tab(Fc, I, Stk0, St0), emul(Is, Cont, Lvs, [Tab|Stk1], Env, Cs, St1); emul_1([?FCALL|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_fcall(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([?TAIL_FCALL|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_tail_fcall(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([?MCALL(M)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_mcall(Is, Cont, Lvs, Stk, Env, Cs, St, M); emul_1([?TAIL_MCALL(M)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_tail_mcall(Is, Cont, Lvs, Stk, Env, Cs, St, M); emul_1([?OP(Op,1)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_op1(Is, Cont, Lvs, Stk, Env, Cs, St, Op); emul_1([?OP(Op,2)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_op2(Is, Cont, Lvs, Stk, Env, Cs, St, Op); emul_1([?PUSH_FDEF(Funref)|Is], Cont, Lvs, Stk, Env, Cs, St0) -> Funref1 = Funref#funref{env=Env}, emul(Is, Cont, Lvs, [Funref1|Stk], Env, Cs, St0); emul_1([?BLOCK(Lsz, Esz, Bis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_block(Is, Cont, Lvs, Stk, Env, Cs, St, Lsz, Esz, Bis); emul_1([?BLOCK_OPEN(Lsz, Esz)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_block_open(Is, Cont, Lvs, Stk, Env, Cs, St, Lsz, Esz); emul_1([?BLOCK_CLOSE|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_block_close(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([?WHILE(Eis, Wis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_while(Is, Cont, Lvs, Stk, Env, Cs, St, Eis, Wis); emul_1([?WHILE_LOOP(Eis, Wis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_while_loop(Is, Cont, Lvs, Stk, Env, Cs, St, Eis, Wis); emul_1([?REPEAT(Ris)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_repeat(Is, Cont, Lvs, Stk, Env, Cs, St, Ris); emul_1([?REPEAT_LOOP(Ris)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_repeat_loop(Is, Cont, Lvs, Stk, Env, Cs, St, Ris); emul_1([?AND_THEN(Then)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_and_then(Is, Cont, Lvs, Stk, Env, Cs, St, Then); emul_1([?OR_ELSE(Else)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_or_else(Is, Cont, Lvs, Stk, Env, Cs, St, Else); emul_1([?IF_TRUE(True)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_if_true(Is, Cont, Lvs, Stk, Env, Cs, St, True); emul_1([?IF(True, False)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_if(Is, Cont, Lvs, Stk, Env, Cs, St, True, False); emul_1([?NFOR(V, Fis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_numfor(Is, Cont, Lvs, Stk, Env, Cs, St, V, Fis); emul_1([?NFOR_LOOP(N,L,S,Fis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_numfor_loop(Is, Cont, Lvs, Stk, Env, Cs, St, N, L, S, Fis); emul_1([?GFOR(Vs, Fis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_genfor(Is, Cont, Lvs, Stk, Env, Cs, St, Vs, Fis); emul_1([?GFOR_CALL(Func, Data, Val, Fis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_genfor_call(Is, Cont, Lvs, Stk, Env, Cs, St, Func, Data, Val, Fis); emul_1([?GFOR_LOOP(Func, Data, Fis)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_genfor_loop(Is, Cont, Lvs, Stk, Env, Cs, St, Func, Data, Fis); emul_1([?BREAK|_], _Cont, Lvs, _Stk, _Env, Cs, St) -> do_break(Lvs, Cs, St); emul_1([?RETURN(Ac)|_], _Cont, _Lvs, Stk, _Env, Cs, St) -> do_return(Ac, Stk, Cs, St); Stack instructions emul_1([?POP|Is], Cont, Lvs, [_|Stk], Env, Cs, St) -> emul(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([?POP2|Is], Cont, Lvs, [_,_|Stk], Env, Cs, St) -> emul(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([?SWAP|Is], Cont, Lvs, [S1,S2|Stk], Env, Cs, St) -> emul(Is, Cont, Lvs, [S2,S1|Stk], Env, Cs, St); emul_1([?DUP|Is], Cont, Lvs, [V|_]=Stk, Env, Cs, St) -> emul(Is, Cont, Lvs, [V|Stk], Env, Cs, St); emul_1([?PUSH_VALS(Vc)|Is], Cont, Lvs, [Vals|Stk0], Env, Cs, St) -> Pop value list off the stack and push Vc vals from it . Stk1 = push_vals(Vc, Vals, Stk0), emul(Is, Cont, Lvs, Stk1, Env, Cs, St); emul_1([?POP_VALS(Vc)|Is], Cont, Lvs, Stk0, Env, Cs, St) -> {Vals,Stk1} = pop_vals(Vc, Stk0), emul(Is, Cont, Lvs, [Vals|Stk1], Env, Cs, St); emul_1([?PUSH_ARGS(Al)|Is], Cont, Lvs, [Args|Stk0], Env, Cs, St) -> Stk1 = push_args(Al, Args, Stk0), emul(Is, Cont, Lvs, Stk1, Env, Cs, St); emul_1([?POP_ARGS(Ac)|Is], Cont, Lvs, Stk0, Env, Cs, St) -> {Args,Stk1} = pop_vals(Ac, Stk0), emul(Is, Cont, Lvs, [Args|Stk1], Env, Cs, St); emul_1([?COMMENT(_)|Is], Cont, Lvs, Stk, Env, Cs, St) -> emul(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([?CURRENT_LINE(Line,File)|Is], Cont, Lvs, Stk, Env, Cs, St) -> do_current_line(Is, Cont, Lvs, Stk, Env, Cs, St, Line, File); emul_1([], [Is|Cont], Lvs, Stk, Env, Cs, St) -> emul(Is, Cont, Lvs, Stk, Env, Cs, St); emul_1([], [], Lvs, Stk, Env, Cs, St) -> {Lvs,Stk,Env,Cs,St}. pop_vals(Count , ) - > { ValList , Stack } . pop_vals(Count , Stack , ValList ) - > { ValList , Stack } . First value is deepest . Always generates list . pop_vals(0, Stk) -> {[],Stk}; pop_vals(C-1, Stk, Vtail). pop_vals(0, Stk, Vs) -> {Vs,Stk}; pop_vals(1, [V|Stk], Vs) -> {[V|Vs],Stk}; pop_vals(2, [V2,V1|Stk], Vs) -> {[V1,V2|Vs],Stk}; pop_vals(C, [V2,V1|Stk], Vs) -> pop_vals(C-2, Stk, [V1,V2|Vs]). push_vals(Count , ValList , Stack ) - > Stack . Push Count values from ValList onto the stack . First value is push_vals(0, _, Stk) -> Stk; push_vals(C, [V|Vs], Stk) -> push_vals(C-1, Vs, [V|Stk]); push_vals(C, [], Stk) -> push_vals(C-1, [], [nil|Stk]). push_args(Varlist , ArgList , Stack ) - > Stack . Use Varlist to push args from ArgList onto the stack . First arg is deepest . Tail of VarList determines whether there are . push_args([_V|Vs], [A|As], Stk) -> push_args(Vs, As, [A|Stk]); push_args([_V|Vs], [], Stk) -> push_args(Vs, [], [nil|Stk]); ... save as list [As|Stk]. do_set_key(Instrs , LocalVars , Stack , Env , State , Table , Key , ) - > do_get_key(Instrs , , Stack , Env , State , Table , Key ) - > do_set_key(Is, Cont, Lvs, Stk, Env, Cs, St0, Tab, Key, Val) -> case luerl_heap:set_table_key(Tab, Key, Val, St0) of {value,_,St1} -> emul(Is, Cont, Lvs, Stk, Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL,?POP|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end. do_get_key(Is, Cont, Lvs, Stk, Env, Cs, St0, Tab, Key) -> case luerl_heap:get_table_key(Tab, Key, St0) of {value,Val,St1} -> emul(Is, Cont, Lvs, [Val|Stk], Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL,?SINGLE|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end. do_op1(Instrs , LocalVars , Stack , Env , State , Op ) - > ReturnFromEmul . do_op2(Instrs , , Stack , Env , State , Op ) - > ReturnFromEmul . do_op1(Is, Cont, Lvs, [A|Stk], Env, Cs, St0, Op) -> case op(Op, A, St0) of {value,Res,St1} -> emul(Is, Cont, Lvs, [Res|Stk], Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL,?SINGLE|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end. do_op2(Is, Cont, Lvs, [A2,A1|Stk], Env, Cs, St0, Op) -> case op(Op, A1, A2, St0) of {value,Res,St1} -> emul(Is, Cont, Lvs, [Res|Stk], Env, Cs, St1); {meta,Meth,Args,St1} -> emul([?FCALL,?SINGLE|Is], Cont, Lvs, [Args,Meth|Stk], Env, Cs, St1); {error,Error,St1} -> lua_error(Error, St1#luerl{stk=Stk,cs=Cs}) end. do_break(LocalVars , CallStack , State ) - > < emul > . do_break(Lvs0, Cs0, St) -> {Bf,Cs1} = find_loop_frame(Cs0, St), #loop_frame{is=Is,cont=Cont,lvs=Lvs1,stk=Stk,env=Env} = Bf, Lvs2 = lists:nthtail(length(Lvs0)-length(Lvs1), Lvs0), emul(Is, Cont, Lvs2, Stk, Env, Cs1, St). do_return(ArgCount , Stack , Callstack , State ) - > < emul > . do_return(Ac, Stk0, Cs0, St0) -> Find the first call frame {Ret,Stk1} = pop_vals(Ac, Stk0), Tfunc = St0#luerl.trace_func, St1 = if is_function(Tfunc) -> Tfunc(?RETURN(Ret), St0#luerl{stk=Stk1,cs=Cs1}); true -> St0 end, #call_frame{is=Is,cont=Cont,lvs=Lvs,env=Env} = Cf, emul(Is, Cont, Lvs, [Ret|Stk1], Env, Cs1, St1#luerl{cs=Cs1}). find_call_frame([#call_frame{}=Cf|Cs], _St) -> {Cf,Cs}; find_call_frame([_|Cs], St) -> find_call_frame(Cs, St). find_loop_frame(Cs, St); find_loop_frame([#loop_frame{}=Bf|Cs], _St) -> {Bf,Cs}; find_loop_frame(Cs, St) -> lua_error({illegal_op,break}, St#luerl{cs=Cs}). do_current_line(Instrs , Continuation , LocalVars , Stack , Env , Stack , State , do_current_line(Is, Cont, Lvs, Stk, Env, Cs0, St0, Line, File) -> Push onto Tfunc = St0#luerl.trace_func, St1 = if is_function(Tfunc) -> Tfunc(?CURRENT_LINE(Line, File), St0#luerl{stk=Stk,cs=Cs1}); true -> St0 end, emul(Is, Cont, Lvs, Stk, Env, Cs1, St1). Push the current line info on the stack replacing an existing one push_current_line([#current_line{}|Cs], Line, File) -> [#current_line{line=Line,file=File}|Cs]; push_current_line(Cs, Line, File) -> [#current_line{line=Line,file=File}|Cs]. do_fcall(Instrs , LocalVars , Stack , Env , State ) - > ReturnFromEmul . do_fcall(Is, Cont, Lvs, [Args,Func|Stk], Env, Cs, St) -> functioncall(Is, Cont, Lvs, Stk, Env, Cs, St, Func, Args). functioncall(Instrs , Cont , LocalVars , , Env , CallStack , State , Func , ) - > This is called from within code and continues with Instrs after call . It must move everything into State . functioncall(Is, Cont, Lvs, Stk, Env, Cs0, St, Func, Args) -> Fr = #call_frame{func=Func,args=Args,lvs=Lvs,env=Env,is=Is,cont=Cont}, Cs1 = [Fr|Cs0], call_function(Func, Args, Stk, Cs1, St). do_tail_fcall(Instrs , Cont , LocalVars , Stack , Env , State ) - > do_tail_fcall(_Is, _Cont, _Lvs, [Args,Func|_Stk], _Env, Cs, St) -> error({tail_fcall,Func,Args,Cs,St}). do_mcall(Instrs , Cont , LocalVars , Stack , Env , State , Method ) - > do_mcall(Is, Cont, Lvs, [Args,Obj|Stk], Env, Cs, St, M) -> methodcall(Is, Cont, Lvs, Stk, Env, Cs, St, Obj, M, Args). methodcall(Instrs , Cont , Var , Stk , Env , State , Object , Method , ) - > This is called from within code and continues with Instrs after call . It must move everything into State . methodcall(Is, Cont, Lvs, Stk, Env, Cs, St0, Obj, Meth, Args) -> io : format("mc1 ~p ~p ~p\n " , [ Obj , Meth , ] ) , case luerl_heap:get_table_key(Obj, Meth, St0) of {value,Func,St1} -> functioncall(Is, Cont, Lvs, Stk, Env, Cs, St1, Func, [Obj|Args]); {meta,Mmeth,Margs,St1} -> io : format("mc3 ~p ~p\n " , [ Mmeth , Margs ] ) , Must first meta method to get function and then call it . Is1 = [?FCALL,?SINGLE,?SWAP,?FCALL|Is], emul(Is1, Cont, Lvs, [Margs,Mmeth,[Obj|Args]|Stk], Env, Cs, St1); lua_error({undefined_method,Obj,Meth}, St1#luerl{stk=Stk,cs=Cs}) end. do_tail_mcall(Instrs , Cont , LocalVars , Stack , Env , State , Method ) - > do_tail_mcall(_Is, _Cont, _Lvs, [Args,Obj|_Stk], _Env, Cs, St, Meth) -> error({tail_mcall,Obj,Meth,Args,Cs,St}). call_function(Function , , Stack , CallStack , State ) - > { Return , State } . call_function(#funref{env=Env}=Funref, Args, Stk, Cs, St0) -> St1 = trace_call(Funref, Args, Stk, Cs, St0), {Func,St2} = luerl_heap:get_funcdef(Funref, St1#luerl{stk=Stk}), call_luafunc(Func, Args, Stk, Env, Cs, St2); call_function(#erl_func{code=Func}=Funref, Args, Stk, Cs, St0) -> St1 = trace_call(Funref, Args, Stk, Cs, St0), call_erlfunc(Func, Args, Stk, Cs, St1); call_function(Func, Args, Stk, Cs, St) -> case luerl_heap:get_metamethod(Func, <<"__call">>, St) of nil -> lua_error({undefined_function,Func}, St#luerl{stk=Stk,cs=Cs}); Meta -> call_function(Meta, [Func|Args], Stk, Cs, St) end. trace_call((Function , , Stack , CallStack , State ) - > State . Trace the function call when required . trace_call(Funref, Args, _Stk, _Cs, St) -> Tfunc = St#luerl.trace_func, if is_function(Tfunc) -> Tfunc({fcall,Funref,Args}, St); true -> St end. call_luafunc(LuaFunc , , Stack , Env , CallStack , State ) - > { Return , State } . call_luafunc(#lua_func{lsz=Lsz,esz=Esz,pars=_Pars,body=Fis}, Args, Stk0, Env0, Cs, St0) -> L = make_loc_frame(Lsz), {Eref,St1} = make_env_frame(Esz, St0), Lvs = [L], Stk1 = [Args|Stk0], Env1 = [Eref|Env0], io : fwrite("fc : ~p\n " , [ { Lvs , Env , St0#luerl.env } ] ) , emul(Fis, [], Lvs, Stk1, Env1, Cs, St1). call_erlfunc(ErlFunc , , Stack , CallStack , State ) - > { Return , State } . Note we leave the call frame to the erlang function on the call call_erlfunc(Func, Args, Stk, Cs0, #luerl{stk=Stk0}=St0) -> case Func(Args, St0#luerl{stk=Stk,cs=Cs0}) of {Ret,St1} -> [#call_frame{is=Is,cont=Cont,lvs=Lvs,env=Env}|Cs1] = Cs0, emul(Is, Cont, Lvs, [Ret|Stk], Env, Cs1, St1#luerl{stk=Stk0,cs=Cs1}); _Other -> lua_error(illegal_return_value, St0#luerl{stk=Stk0,cs=tl(Cs0)}) end. do_block(Instrs , LocalVars , Stack , Env , State , LocalSize , EnvSize , BlockInstrs ) - > < emul > . do_block(Is, Cont, Lvs, Stk, Env, Cs, St0, Lsz, Esz, Bis) -> L = make_loc_frame(Lsz), {Eref,St1} = make_env_frame(Esz, St0), emul(Bis, [Is|Cont], [L|Lvs], Stk, [Eref|Env], Cs, St1). do_block_open(Instrs , LocalVars , Stack , Env , State , LocalSize , EnvSize ) - > < emul > . do_block_open(Is, Cont, Lvs, Stk, Env, Cs, St0, Lsz, Esz) -> L = make_loc_frame(Lsz), {Eref,St1} = make_env_frame(Esz, St0), emul(Is, Cont, [L|Lvs], Stk, [Eref|Env], Cs, St1). do_block_close(Instrs , , Stack , Env , State , LocalSize , EnvSize ) - > < emul > . do_block_close(Is, Cont, [_|Lvs], Stk, [_|Env], Cs, St) -> emul(Is, Cont, Lvs, Stk, Env, Cs, St). make_env_frame(0, St) -> {not_used,St}; make_env_frame(Esz, St) -> { Eref , St } . make_loc_frame(0) -> not_used; make_loc_frame(Lsz) -> erlang:make_tuple(Lsz, nil). do_while(Instrs , Cont , LocalVars , Stack , Env , State , WhileEis , WhileBis ) - > do_while(Is, Cont, Lvs, Stk, Env, Cs0, St, Eis, Wis) -> Fr = #loop_frame{lvs=Lvs,stk=Stk,env=Env,is=Is,cont=Cont}, Cs1 = [Fr|Cs0], emul(Eis, [[?WHILE_LOOP(Eis, Wis)|Is]|Cont], Lvs, Stk, Env, Cs1, St). do_while_loop(Is, Cont, Lvs, [Val|Stk], Env, Cs, St, Eis, Wis) -> case boolean_value(Val) of true -> emul(Wis, [Eis,[?WHILE_LOOP(Eis, Wis)|Is]|Cont], Lvs, Stk, Env, Cs, St); false -> emul([?BREAK|Is], Cont, Lvs, Stk, Env, Cs, St) end. do_repeat(Instrs , Cont , LocalVars , Stack , Env , State , RepeatInstrs ) - > do_repeat(Is, Cont, Lvs, Stk, Env, Cs0, St, Ris) -> Fr = #loop_frame{lvs=Lvs,stk=Stk,env=Env,is=Is,cont=Cont}, Cs1 = [Fr|Cs0], emul(Ris, [[?REPEAT_LOOP(Ris)|Is]|Cont], Lvs, Stk, Env, Cs1, St). do_repeat_loop(Is, Cont, Lvs, [Val|Stk], Env, Cs, St, Ris) -> case boolean_value(Val) of true -> emul([?BREAK|Is], Cont, Lvs, Stk, Env, Cs, St); false -> emul(Ris, [[?REPEAT_LOOP(Ris)|Is]|Cont], Lvs, Stk, Env, Cs, St) end. do_and_then(Instrs , Continuation , LocalVars , Stack , Env , State , ) - > do_or_else(Instrs , Continuation , LocalVars , Stack , Env , State , ElseInstrs ) - > do_and_then(Is, Cont, Lvs, [Val|Stk1]=Stk0, Env, Cs, St, Then) -> case boolean_value(Val) of true -> emul(Then, [Is|Cont], Lvs, Stk1, Env, Cs, St); false -> emul(Is, Cont, Lvs, Stk0, Env, Cs, St) end. do_or_else(Is, Cont, Lvs, [Val|Stk1]=Stk0, Env, Cs, St, Else) -> case boolean_value(Val) of true -> emul(Is, Cont, Lvs, Stk0, Env, Cs, St); false -> emul(Else, [Is|Cont], Lvs, Stk1, Env, Cs, St) end. do_if(Instrs , Continuation , LocalVars , Stack , Env , State , TrueInstrs ) - > do_if_true(Is, Cont, Lvs, [Val|Stk], Env, Cs, St, True) -> case boolean_value(Val) of true -> emul(True, [Is|Cont], Lvs, Stk, Env, Cs, St); false -> emul(Is, Cont, Lvs, Stk, Env, Cs, St) end. do_if(Instrs , LocalVars , Stack , Env , State , TrueInstrs , FalseInstrs ) - > do_if(Is, Cont, Lvs0, [Val|Stk0], Env0, Cs, St0, True, False) -> case boolean_value(Val) of true -> emul(True, [Is|Cont], Lvs0, Stk0, Env0, Cs, St0); false -> emul(False, [Is|Cont], Lvs0, Stk0, Env0, Cs, St0) end. do_if(Blocks , Else , Lvs , Stk , Env , St ) - > do_if_blocks(Blocks , Else , Lvs , Stk , Env , St ) . do_if_blocks([{T , B}|Ts ] , Else , Lvs0 , Stk0 , Env0 , St0 ) - > { Lvs1,[Val|Stk1],Env1,St1 } = emul(T , Lvs0 , Stk0 , Env0 , St0 ) , true - > emul(B , Lvs1 , Stk1 , Env1 , St1 ) ; false - > do_if_blocks(Ts , Lvs1 , Stk1 , Env1 , St1 ) do_if_block([?BLOCK(Lsz , Esz , ) ] , Lvs0 , Stk0 , Env0 , St0 , Is ) - > { Lvs1,Stk1,Env1,St1 } = do_block(Bis , Lvs0 , Stk0 , Env0 , St0 , Lsz , Esz ) , emul(Is , Lvs1 , Stk1 , Env1 , St1 ) ; do_if_block(Bis , Lvs0 , Stk0 , Env0 , St0 , Is ) - > { Lvs1,Stk1,Env1,St1 } = emul(Bis , Lvs0 , Stk0 , Env0 , St0 ) , emul(Is , Lvs1 , Stk1 , Env1 , St1 ) . do_numfor(Instrs , LocalVars , Stack , Env , State , Varname , FromInstrs ) - > do_numfor(Is, Cont, Lvs, [Step,Limit,Init|Stk], Env, Cs0, St, _, Fis) -> First check if we have numbers . case luerl_lib:args_to_numbers([Init,Limit,Step]) of [I,L,S] -> Fr = #loop_frame{lvs=Lvs,stk=Stk,env=Env,is=Is,cont=Cont}, Cs1 = [Fr|Cs0], do_numfor_loop(Is, Cont, Lvs, Stk, Env, Cs1, St, I, L, S, Fis); error -> badarg_error(loop, [Init,Limit,Step], St#luerl{cs=Cs0}) end. do_numfor_loop(Is, Cont, Lvs, Stk, Env, Cs, St, N, Limit, Step, Fis) -> emul(Fis, [[?NFOR_LOOP(N+Step, Limit, Step, Fis)|Is]|Cont], Lvs, [N|Stk], Env, Cs, St); emul(Fis, [[?NFOR_LOOP(N+Step, Limit, Step, Fis)|Is]|Cont], Lvs, [N|Stk], Env, Cs, St); emul([?BREAK|Is], Cont, Lvs, Stk, Env, Cs, St) end. do_genfor(Instrs , LocalVars , Stack , Env , CallStack , State , Vars , FromInstrs ) - > < emul > do_genfor(Is, Cont, Lvs, [Val|Stk], Env, Cs0, St, _, Fis) -> Sneaky , export Func , Data , Var [Func] -> Data = nil, Var = nil; [Func,Data] -> Var = nil; [Func,Data,Var|_] -> ok; Func -> Data = nil, Var = nil end, Fr = #loop_frame{lvs=Lvs,stk=Stk,env=Env,is=Is,cont=Cont}, Cs1 = [Fr|Cs0], do_genfor_call(Is, Cont, Lvs, Stk, Env, Cs1, St, Func, Data, Var, Fis). do_genfor_call(Is, Cont, Lvs, Stk, Env, Cs, St, Func, Data, Val, Fis) -> emul([?FCALL,?GFOR_LOOP(Func, Data, Fis)|Is], Cont, Lvs, [[Data,Val],Func|Stk], Env, Cs, St). do_genfor_loop(Is, Cont, Lvs, [Vals|Stk], Env, Cs, St, Func, Data, Fis) -> case boolean_value(Vals) of true -> emul(Fis, [[?GFOR_CALL(Func,Data,hd(Vals),Fis)|Is]|Cont], Lvs, [Vals|Stk], Env, Cs, St); false -> emul([?BREAK|Is], Cont, Lvs, Stk, Env, Cs, St) end. build_tab(FieldCount , Index , Stack , State ) - > { TableRef , Stack , State } . FieldCount is how many Key / Value pairs are on the stack , Index is the index of the next value in the acc . build_tab(Fc, I, [Last|Stk0], St0) -> Fs0 = build_tab_last(I, Last), {Fs1,Stk1} = build_tab_loop(Fc, Stk0, Fs0), io : : ~p\n " , [ { Fc , I , Acc , Fs0,Fs1 } ] ) , {Tref,St1} = luerl_heap:alloc_table(Fs1, St0), {Tref,Stk1,St1}. build_tab_last(I, [V|Vs]) -> [{I,V}|build_tab_last(I+1, Vs)]; build_tab_last(_, []) -> []; build_tab_last(_, Last) -> error({boom,build_tab_acc,Last}). build_tab_loop(0, Stk, Fs) -> {Fs,Stk}; build_tab_loop(C, [V,K|Stk], Fs) -> build_tab_loop(C-1, Stk, [{K,V}|Fs]). op(Op , Arg , State ) - > OpReturn . op(Op , Arg1 , , State ) - > OpReturn . = { value , Ret , State } | { meta , Method , , State } | op('-', A, St) -> numeric_op('-', A, St, <<"__unm">>, fun (N) -> -N end); op('not', A, St) -> {value,not ?IS_TRUE(A),St}; op('~', A, St) -> integer_op('~', A, St, <<"__bnot">>, fun (N) -> bnot(N) end); op('#', A, St) -> length_op('#', A, St); op(Op, A, St) -> {error,{badarg,Op,[A]},St}. op('+', A1, A2, St) -> numeric_op('+', A1, A2, St, <<"__add">>, fun (N1,N2) -> N1+N2 end); op('-', A1, A2, St) -> numeric_op('-', A1, A2, St, <<"__sub">>, fun (N1,N2) -> N1-N2 end); op('*', A1, A2, St) -> numeric_op('*', A1, A2, St, <<"__mul">>, fun (N1,N2) -> N1*N2 end); op('/', A1, A2, St) -> numeric_op('/', A1, A2, St, <<"__div">>, fun (N1,N2) -> N1/N2 end); op('//', A1, A2, St) -> numeric_op('//', A1, A2, St, <<"__idiv">>, fun (N1,N2) when is_integer(N1), is_integer(N2) -> Idiv = N1 div N2, Irem = N1 rem N2, if Irem =:= 0 -> Idiv; Idiv < 0 -> Idiv - 1; true -> Idiv end; (N1,N2) -> 0.0 + floor(N1/N2) end); fun (N1,N2) when is_integer(N1), is_integer(N2) -> Irem = N1 rem N2, if (Irem < 0) and (N2 >= 0) -> Irem + N2; (Irem > 0) and (N2 < 0) -> Irem + N2; true -> Irem end; if < 0 - > > 0 - > (N1,N2) -> N1 - floor(N1/N2)*N2 end); op('^', A1, A2, St) -> numeric_op('^', A1, A2, St, <<"__pow">>, fun (N1,N2) -> math:pow(N1, N2) end); Bitwise operators . op('&', A1, A2, St) -> integer_op('&', A1, A2, St, <<"__band">>, fun (N1,N2) -> N1 band N2 end); op('|', A1, A2, St) -> integer_op('|', A1, A2, St, <<"__bor">>, fun (N1,N2) -> N1 bor N2 end); op('~', A1, A2, St) -> integer_op('~', A1, A2, St, <<"__bxor">>, fun (N1,N2) -> N1 bxor N2 end); op('<<', A1, A2, St) -> integer_op('<<', A1, A2, St, <<"__shl">>, fun (N1,N2) -> N1 bsl N2 end); op('>>', A1, A2, St) -> integer_op('>>', A1, A2, St, <<"__shr">>, fun (N1,N2) -> N1 bsr N2 end); op('==', A1, A2, St) -> eq_op('==', A1, A2, St); op('~=', A1, A2, St) -> neq_op('~=', A1, A2, St); op('<=', A1, A2, St) -> le_op('<=', A1, A2, St); op('>=', A1, A2, St) -> le_op('>=', A2, A1, St); op('<', A1, A2, St) -> lt_op('<', A1, A2, St); op('>', A1, A2, St) -> lt_op('>', A2, A1, St); op('..', A1, A2, St) -> concat_op(A1, A2, St); op(Op, A1, A2, St) -> {error,{badarg,Op,[A1,A2]}, St}. -ifndef(HAS_FLOOR). Floor does not exist before 20 so we need to do it ourselves . floor(N) when is_integer(N) -> N; floor(N) when is_float(N) -> round(N - 0.5). -endif. numeric_op(Op , Arg , State , Event , Raw ) - > OpReturn . numeric_op(Op , Arg , Arg , State , Event , Raw ) - > OpReturn . = { value , Ret , State } | { meta , Method , , State } | length_op(_Op, A, St) when is_binary(A) -> {value,byte_size(A),St}; length_op(_Op, A, St) -> case luerl_heap:get_metamethod(A, <<"__len">>, St) of nil -> if ?IS_TREF(A) -> {value,luerl_lib_table:raw_length(A, St),St}; true -> {error,{badarg,'#',[A]}, St} end; Meth -> {meta,Meth,[A],St} end. numeric_op(Op, A, St, E, Raw) -> case luerl_lib:arg_to_number(A) of error -> op_meta(Op, A, E, St); N -> {value,Raw(N),St} end. numeric_op(Op, A1, A2, St, E, Raw) -> case luerl_lib:args_to_numbers(A1, A2) of [N1,N2] -> {value,Raw(N1, N2),St}; error -> op_meta(Op, A1, A2, E, St) end. integer_op(Op, A, St, E, Raw) -> case luerl_lib:arg_to_integer(A) of error -> op_meta(Op, A, E, St); N -> {value,Raw(N),St} end. integer_op(Op, A1, A2, St, E, Raw) -> case luerl_lib:args_to_integers(A1, A2) of [N1,N2] -> {value,Raw(N1, N2),St}; error -> op_meta(Op, A1, A2, E, St) end. eq_op(_Op, A1, A2, St) when A1 == A2 -> {value,true,St}; eq_op(_Op, A1, A2, St) when ?IS_TREF(A1), ?IS_TREF(A2) ; ?IS_USDREF(A1), ?IS_USDREF(A2) -> case get_eqmetamethod(A1, A2, St) of nil -> {value,false,St}; Meth -> Func = fun (Args, St0) -> {Ret,St1} = functioncall(Meth, Args, St0), {[boolean_value(Ret)],St1} end, {meta,#erl_func{code=Func},[A1,A2],St} end; eq_op(_, _, _, St) -> {value,false,St}. neq_op(_Op, A1, A2, St) when A1 == A2 -> {value,false,St}; neq_op(_Op, A1, A2, St) when ?IS_TREF(A1), ?IS_TREF(A2) ; ?IS_USDREF(A1), ?IS_USDREF(A2) -> case get_eqmetamethod(A1, A2, St) of nil -> {value,true,St}; Meth -> Func = fun (Args, St0) -> {Ret,St1} = functioncall(Meth, Args, St0), {[not boolean_value(Ret)],St1} end, {meta,#erl_func{code=Func},[A1,A2],St} end; neq_op(_, _, _, St) -> {value,true,St}. get_eqmetamethod(A1, A2, St) -> case luerl_heap:get_metamethod(A1, <<"__eq">>, St) of nil -> nil; Meth -> case luerl_heap:get_metamethod(A2, <<"__eq">>, St) of _ -> nil end end. lt_op(_Op, A1, A2, St) when is_number(A1), is_number(A2) -> {value,A1 < A2,St}; lt_op(_Op, A1, A2, St) when is_binary(A1), is_binary(A2) -> {value,A1 < A2,St}; lt_op(Op, A1, A2, St) -> op_meta(Op, A1, A2, <<"__lt">>, St). le_op(_Op, A1, A2, St) when is_number(A1), is_number(A2) -> {value,A1 =< A2,St}; le_op(_Op, A1, A2, St) when is_binary(A1), is_binary(A2) -> {value,A1 =< A2,St}; le_op(Op, A1, A2, St) -> Must check for first _ _ le then _ _ lt metamethods . case luerl_heap:get_metamethod(A1, A2, <<"__le">>, St) of nil -> case luerl_heap:get_metamethod(A1, A2, <<"__lt">>, St) of nil -> {error,{badarg,Op,[A1,A2]}, St}; Meth -> {meta,Meth,[A2,A1],St} end; Meth -> {meta,Meth,[A1,A2],St} end. concat_op(A1, A2, St) -> case luerl_lib:conv_list([A1,A2], [lua_string,lua_string]) of [S1,S2] -> {value,<<S1/binary,S2/binary>>,St}; error -> op_meta('..', A1, A2, <<"__concat">>, St) end. op_meta(Op, A, E, St) -> case luerl_heap:get_metamethod(A, E, St) of nil -> {error,{badarg,Op,[A]}, St}; Meth -> {meta,Meth,[A],St} end. op_meta(Op, A1, A2, E, St) -> case luerl_heap:get_metamethod(A1, A2, E, St) of nil -> {error,{badarg,Op,[A1,A2]},St}; Meth -> {meta,Meth,[A1,A2],St} end. boolean_value([nil|_]) -> false; boolean_value([false|_]) -> false; boolean_value([_|_]) -> true; boolean_value([]) -> false; boolean_value(nil) -> false; boolean_value(false) -> false; boolean_value(_) -> true. first_value([V|_]) -> V; first_value([]) -> nil. multiple_value(V) when not is_list(V) -> [V].
39cce6a14c69cd1303b1df0b638fd9635ad40d6b93889da3666654102073f5fa
unisonweb/unison
Ann.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeFamilies # # LANGUAGE ViewPatterns # module Unison.Parser.Ann where import qualified Unison.Lexer.Pos as L data Ann { sig : : String , start : : L.Pos , end : : L.Pos } | External | Ann {start :: L.Pos, end :: L.Pos} deriving (Eq, Ord, Show) startingLine :: Ann -> Maybe L.Line startingLine (Ann (L.line -> line) _) = Just line startingLine _ = Nothing instance Monoid Ann where mempty = External instance Semigroup Ann where Ann s1 e1 <> Ann s2 e2 = Ann (min s1 s2) (max e1 e2) -- If we have a concrete location from a file, use it External <> a = a a <> External = a Intrinsic <> a = a a <> Intrinsic = a -- | Checks whether an annotation contains a given position -- i.e. pos ∈ [start, end) -- -- >>> Intrinsic `contains` L.Pos 1 1 -- False -- -- >>> External `contains` L.Pos 1 1 -- False -- > > > ( L.Pos 0 0 ) ( L.Pos 0 10 ) ` contains ` L.Pos 0 5 -- True -- > > > ( L.Pos 0 0 ) ( L.Pos 0 10 ) ` contains ` L.Pos 0 10 -- False contains :: Ann -> L.Pos -> Bool contains Intrinsic _ = False contains External _ = False contains (Ann start end) p = start <= p && p < end -- | Checks whether an annotation contains another annotation. -- -- i.e. pos ∈ [start, end) -- > > > Intrinsic ` encompasses ` ( L.Pos 1 1 ) ( L.Pos 2 1 ) -- Nothing -- > > > External ` encompasses ` ( L.Pos 1 1 ) ( L.Pos 2 1 ) -- Nothing -- > > > ( L.Pos 0 0 ) ( L.Pos 0 10 ) ` encompasses ` ( L.Pos 0 1 ) ( L.Pos 0 5 ) -- Just True -- > > > ( L.Pos 1 0 ) ( L.Pos 1 10 ) ` encompasses ` ( L.Pos 0 0 ) ( L.Pos 2 0 ) -- Just False encompasses :: Ann -> Ann -> Maybe Bool encompasses Intrinsic _ = Nothing encompasses External _ = Nothing encompasses _ Intrinsic = Nothing encompasses _ External = Nothing encompasses (Ann start1 end1) (Ann start2 end2) = Just $ start1 <= start2 && end1 >= end2
null
https://raw.githubusercontent.com/unisonweb/unison/59e8a256934b39ae50c8e15e259e66dc00c217c1/unison-syntax/src/Unison/Parser/Ann.hs
haskell
# LANGUAGE OverloadedStrings # If we have a concrete location from a file, use it | Checks whether an annotation contains a given position i.e. pos ∈ [start, end) >>> Intrinsic `contains` L.Pos 1 1 False >>> External `contains` L.Pos 1 1 False True False | Checks whether an annotation contains another annotation. i.e. pos ∈ [start, end) Nothing Nothing Just True Just False
# LANGUAGE TypeFamilies # # LANGUAGE ViewPatterns # module Unison.Parser.Ann where import qualified Unison.Lexer.Pos as L data Ann { sig : : String , start : : L.Pos , end : : L.Pos } | External | Ann {start :: L.Pos, end :: L.Pos} deriving (Eq, Ord, Show) startingLine :: Ann -> Maybe L.Line startingLine (Ann (L.line -> line) _) = Just line startingLine _ = Nothing instance Monoid Ann where mempty = External instance Semigroup Ann where Ann s1 e1 <> Ann s2 e2 = Ann (min s1 s2) (max e1 e2) External <> a = a a <> External = a Intrinsic <> a = a a <> Intrinsic = a > > > ( L.Pos 0 0 ) ( L.Pos 0 10 ) ` contains ` L.Pos 0 5 > > > ( L.Pos 0 0 ) ( L.Pos 0 10 ) ` contains ` L.Pos 0 10 contains :: Ann -> L.Pos -> Bool contains Intrinsic _ = False contains External _ = False contains (Ann start end) p = start <= p && p < end > > > Intrinsic ` encompasses ` ( L.Pos 1 1 ) ( L.Pos 2 1 ) > > > External ` encompasses ` ( L.Pos 1 1 ) ( L.Pos 2 1 ) > > > ( L.Pos 0 0 ) ( L.Pos 0 10 ) ` encompasses ` ( L.Pos 0 1 ) ( L.Pos 0 5 ) > > > ( L.Pos 1 0 ) ( L.Pos 1 10 ) ` encompasses ` ( L.Pos 0 0 ) ( L.Pos 2 0 ) encompasses :: Ann -> Ann -> Maybe Bool encompasses Intrinsic _ = Nothing encompasses External _ = Nothing encompasses _ Intrinsic = Nothing encompasses _ External = Nothing encompasses (Ann start1 end1) (Ann start2 end2) = Just $ start1 <= start2 && end1 >= end2
8b69f3c8dfef7cb5a9ad0c1d82e895dd20a3778f07715c69712b5d3916f330e4
nklein/userial
peek.lisp
Copyright ( c ) 2011 nklein software MIT License . See included LICENSE.txt file for licensing details . (in-package :userial) (defmacro with-peek-buffer (() &body body) `(with-buffer (make-array (list (buffer-capacity)) :element-type '(unsigned-byte 8) :displaced-to *buffer* :fill-pointer (buffer-length) :adjustable nil) ,@body)) (defun peek (type &rest rest &key &allow-other-keys) (with-peek-buffer () (apply #'unserialize type rest)))
null
https://raw.githubusercontent.com/nklein/userial/dc34fc73385678a61c39e98f77a4443433eedb1d/userial/peek.lisp
lisp
Copyright ( c ) 2011 nklein software MIT License . See included LICENSE.txt file for licensing details . (in-package :userial) (defmacro with-peek-buffer (() &body body) `(with-buffer (make-array (list (buffer-capacity)) :element-type '(unsigned-byte 8) :displaced-to *buffer* :fill-pointer (buffer-length) :adjustable nil) ,@body)) (defun peek (type &rest rest &key &allow-other-keys) (with-peek-buffer () (apply #'unserialize type rest)))