text
stringlengths
12
786k
let vlib t = t . vlib
let impl t = t . impl
let impl_cm_kind t = t . impl_cm_kind
let impl_modules t m = match t with | None -> m | Some t -> Modules . impl ~ vlib : t . vlib_modules m
let make ~ vlib ~ impl ~ vlib_modules ~ vlib_foreign_objects = let impl_cm_kind = let vlib_info = Lib . info vlib in let { Mode . Dict . byte ; native = _ } = Lib_info . modes vlib_info in Mode . cm_kind ( if byte then Byte else Native ) in let vlib_obj_map = Modules . obj_map vlib_modules ~ f ( : function | Normal m -> m | _ -> assert false ) |> Module . Obj_map . fold ~ init : Module_name . Unique . Map . empty ~ f ( : fun m acc -> Module_name . Unique . Map . add_exn acc ( Module . obj_name m ) m ) in { impl ; impl_cm_kind ; vlib ; vlib_modules ; vlib_foreign_objects ; vlib_obj_map }
let vlib_stubs_o_files = function | None -> [ ] | Some t -> t . vlib_foreign_objects
let vlib_obj_map t = t . vlib_obj_map
module type ViolationArg = sig include MyARG . S with module Edge = MyARG . InlineEdge val prev : Node . t -> ( Edge . t * Node . t ) list val violations : Node . t list end
let find_sinks ( type node ) ( module Arg : ViolationArg with type Node . t = node ) = let module NHT = BatHashtbl . Make ( Arg . Node ) in let non_sinks = NHT . create 100 in let rec iter_node node = if not ( NHT . mem non_sinks node ) then begin NHT . replace non_sinks node ( ) ; List . iter ( fun ( _ , prev_node ) -> iter_node prev_node ) ( Arg . prev node ) end in List . iter iter_node Arg . violations ; fun n -> not ( NHT . mem non_sinks n )
module type Feasibility = sig module Node : MyARG . Node type result = | Feasible | Infeasible of ( Node . t * MyARG . inline_edge * Node . t ) list | Unknown val check_path : ( Node . t * MyARG . inline_edge * Node . t ) list -> result end
module UnknownFeasibility ( Node : MyARG . Node ) : Feasibility with module Node = Node = struct module Node = Node type result = | Feasible | Infeasible of ( Node . t * MyARG . inline_edge * Node . t ) list | Unknown let check_path _ = Unknown end
module type PathArg = MyARG . S with module Edge = MyARG . InlineEdge
type ' node result = | Feasible of ( module PathArg with type Node . t = ' node ) | Infeasible of ( ' node * MyARG . inline_edge * ' node ) list | Unknown
let find_path ( type node ) ( module Arg : ViolationArg with type Node . t = node ) ( module Feasibility : Feasibility with type Node . t = node ) : node result = let module NHT = BatHashtbl . Make ( Arg . Node ) in let rec trace_path next_nodes node2 = if NHT . mem next_nodes node2 then begin let ( edge , next_node ) = NHT . find next_nodes node2 in ( node2 , edge , next_node ) :: trace_path next_nodes next_node end else [ ] in let print_path path = List . iter ( fun ( n1 , e , n2 ) -> ignore ( Pretty . printf " % s [ =% s ] => % s \ n " ( Arg . Node . to_string n1 ) ( Arg . Edge . to_string e ) ( Arg . Node . to_string n2 ) ) ) path in let find_path nodes = let next_nodes = NHT . create 100 in let itered_nodes = NHT . create 100 in let rec bfs curs nexts = match curs with | node :: curs ' -> if Arg . Node . equal node Arg . main_entry then raise Found else if not ( NHT . mem itered_nodes node ) then begin NHT . replace itered_nodes node ( ) ; List . iter ( fun ( edge , prev_node ) -> if not ( NHT . mem itered_nodes prev_node ) then NHT . replace next_nodes prev_node ( edge , node ) ) ( Arg . prev node ) ; bfs curs ' ( List . map snd ( Arg . prev node ) @ nexts ) end else bfs curs ' nexts | [ ] -> match nexts with | [ ] -> ( ) | _ -> bfs nexts [ ] in try bfs nodes [ ] ; None with | Found -> Some ( trace_path next_nodes Arg . main_entry ) in begin match find_path Arg . violations with | Some path -> print_path path ; begin match Feasibility . check_path path with | Feasibility . Feasible -> print_endline " feasible " ; let module PathArg = struct module Node = Arg . Node module Edge = Arg . Edge let main_entry = BatTuple . Tuple3 . first ( List . hd path ) let next = let module NHT = BatHashtbl . Make ( Node ) in let next = NHT . create ( List . length path ) in List . iter ( fun ( n1 , e , n2 ) -> NHT . modify_def [ ] n1 ( fun nexts -> ( e , n2 ) :: nexts ) next ) path ; ( fun n -> NHT . find_default next n [ ] ) end in Feasible ( module PathArg ) | Feasibility . Infeasible subpath -> print_endline " infeasible " ; print_path subpath ; Infeasible subpath | Feasibility . Unknown -> print_endline " unknown " ; Unknown end | None -> Unknown end
module WP ( Node : MyARG . Node ) : Feasibility with module Node = Node = struct module Node = Node open Z3 open Cil let cfg = [ ( " model " , " true " ) ; ( " unsat_core " , " true " ) ; ] let ctx = mk_context cfg type var = varinfo module Var = CilType . Varinfo module type Env = sig type t val empty : t val get_const : t -> var -> Expr . expr val freshen : t -> var -> t end module Env : Env = struct module VarMap = Map . Make ( Var ) type t = Expr . expr VarMap . t let empty = VarMap . empty let get_name x = x . vname let get_const m x = match VarMap . find_opt x m with | Some x -> x | None -> Arithmetic . Integer . mk_const_s ctx ( get_name x ) let sort = Arithmetic . Integer . mk_sort ctx let freshen env x = VarMap . add x ( Expr . mk_fresh_const ctx ( get_name x ) sort ) env end let bool_to_int expr = Boolean . mk_ite ctx expr ( Arithmetic . Integer . mk_numeral_i ctx 1 ) ( Arithmetic . Integer . mk_numeral_i ctx 0 ) let int_to_bool expr = Boolean . mk_distinct ctx [ expr ; Arithmetic . Integer . mk_numeral_i ctx 0 ] let rec exp_to_expr env = function | Const ( CInt64 ( i , _ , _ ) ) -> Arithmetic . Integer . mk_numeral_s ctx ( Int64 . to_string i ) | Lval ( Var v , NoOffset ) -> Env . get_const env v | BinOp ( PlusA , e1 , e2 , TInt _ ) -> Arithmetic . mk_add ctx [ exp_to_expr env e1 ; exp_to_expr env e2 ] | BinOp ( MinusA , e1 , e2 , TInt _ ) -> Arithmetic . mk_sub ctx [ exp_to_expr env e1 ; exp_to_expr env e2 ] | BinOp ( Mult , e1 , e2 , TInt _ ) -> Arithmetic . mk_mul ctx [ exp_to_expr env e1 ; exp_to_expr env e2 ] | BinOp ( Eq , e1 , e2 , TInt _ ) -> bool_to_int ( Boolean . mk_eq ctx ( exp_to_expr env e1 ) ( exp_to_expr env e2 ) ) | BinOp ( Ne , e1 , e2 , TInt _ ) -> bool_to_int ( Boolean . mk_distinct ctx [ exp_to_expr env e1 ; exp_to_expr env e2 ] ) | BinOp ( Gt , e1 , e2 , TInt _ ) -> bool_to_int ( Arithmetic . mk_gt ctx ( exp_to_expr env e1 ) ( exp_to_expr env e2 ) ) | BinOp ( Lt , e1 , e2 , TInt _ ) -> bool_to_int ( Arithmetic . mk_lt ctx ( exp_to_expr env e1 ) ( exp_to_expr env e2 ) ) | BinOp ( Ge , e1 , e2 , TInt _ ) -> bool_to_int ( Arithmetic . mk_ge ctx ( exp_to_expr env e1 ) ( exp_to_expr env e2 ) ) | BinOp ( Le , e1 , e2 , TInt _ ) -> bool_to_int ( Arithmetic . mk_le ctx ( exp_to_expr env e1 ) ( exp_to_expr env e2 ) ) | UnOp ( LNot , e , TInt _ ) -> bool_to_int ( Boolean . mk_not ctx ( int_to_bool ( exp_to_expr env e ) ) ) | e -> failwith @@ Pretty . sprint ~ width : 80 @@ Pretty . dprintf " exp_to_expr : % a " Cil . d_exp e let get_arg_vname i = Goblintutil . create_var ( Cil . makeVarinfo false ( " _arg " ^ string_of_int i ) Cil . intType ) let return_vname = Goblintutil . create_var ( Cil . makeVarinfo false " _return " Cil . intType ) let wp_assert env ( from_node , ( edge : MyARG . inline_edge ) , _ ) = match edge with | MyARG . CFGEdge ( MyCFG . Assign ( ( Var v , NoOffset ) , e ) ) -> let env ' = Env . freshen env v in ( env ' , [ Boolean . mk_eq ctx ( Env . get_const env v ) ( exp_to_expr env ' e ) ] ) | MyARG . CFGEdge ( MyCFG . Test ( e , true ) ) -> ( env , [ Boolean . mk_distinct ctx [ exp_to_expr env e ; Arithmetic . Integer . mk_numeral_i ctx 0 ] ] ) | MyARG . CFGEdge ( MyCFG . Test ( e , false ) ) -> ( env , [ Boolean . mk_eq ctx ( exp_to_expr env e ) ( Arithmetic . Integer . mk_numeral_i ctx 0 ) ] ) | MyARG . CFGEdge ( MyCFG . Entry fd ) -> let env ' = List . fold_left ( fun acc formal -> Env . freshen acc formal ) env fd . sformals in let eqs = List . mapi ( fun i formal -> let arg_vname = get_arg_vname i in Boolean . mk_eq ctx ( Env . get_const env formal ) ( Env . get_const env ' arg_vname ) ) fd . sformals in ( env ' , eqs ) | MyARG . InlineEntry args -> let env ' = BatList . fold_lefti ( fun acc i arg -> let arg_vname = get_arg_vname i in Env . freshen acc arg_vname ) env args in let eqs = List . mapi ( fun i arg -> let arg_vname = get_arg_vname i in Boolean . mk_eq ctx ( Env . get_const env arg_vname ) ( exp_to_expr env ' arg ) ) args in ( env ' , eqs ) | MyARG . CFGEdge ( MyCFG . Ret ( None , fd ) ) -> ( env , [ ] ) | MyARG . CFGEdge ( MyCFG . Ret ( Some e , fd ) ) -> let env ' = Env . freshen env return_vname in ( env ' , [ Boolean . mk_eq ctx ( Env . get_const env return_vname ) ( exp_to_expr env ' e ) ] ) | MyARG . InlineReturn None -> ( env , [ ] ) | MyARG . InlineReturn ( Some ( Var v , NoOffset ) ) -> let env ' = Env . freshen env v in ( env ' , [ Boolean . mk_eq ctx ( Env . get_const env v ) ( Env . get_const env ' return_vname ) ] ) | _ -> failwith @@ Pretty . sprint ~ width : 80 @@ Pretty . dprintf " wp_assert : % a " MyARG . pretty_inline_edge edge let const_get_symbol ( expr : Expr . expr ) : Symbol . symbol = assert ( Expr . is_const expr ) ; let func_decl = Expr . get_func_decl expr in FuncDecl . get_name func_decl type result = | Feasible | Infeasible of ( Node . t * MyARG . inline_edge * Node . t ) list | Unknown let wp_path path = let solver = Solver . mk_simple_solver ctx in let rec iter_wp revpath i env = match revpath with | [ ] -> Feasible | step :: revpath ' -> let ( env ' , asserts ) = wp_assert env step in begin match asserts with | [ ] -> iter_wp revpath ' ( i - 1 ) env ' | [ expr ] -> do_assert revpath ' i env ' expr | exprs -> let expr = Boolean . mk_and ctx exprs in do_assert revpath ' i env ' expr end and do_assert revpath ' i env ' expr = Printf . printf " % d : % s \ n " i ( Expr . to_string expr ) ; let track_const = Boolean . mk_const ctx ( Symbol . mk_int ctx i ) in Solver . assert_and_track solver expr track_const ; let status = Solver . check solver [ ] in Printf . printf " % d : % s \ n " i ( Solver . string_of_status status ) ; match Solver . check solver [ ] with | Solver . SATISFIABLE -> Printf . printf " % d : % s \ n " i ( Model . to_string ( BatOption . get @@ Solver . get_model solver ) ) ; iter_wp revpath ' ( i - 1 ) env ' | Solver . UNSATISFIABLE -> let extract_track expr = assert ( Expr . is_const expr ) ; let symbol = const_get_symbol expr in assert ( Symbol . is_int_symbol symbol ) ; Symbol . get_int symbol in let unsat_core = Solver . get_unsat_core solver in let unsat_core_is = unsat_core |> List . map extract_track |> List . sort compare in unsat_core_is |> List . map string_of_int |> String . concat " " |> print_endline ; let ( mini , maxi ) = BatList . min_max unsat_core_is in let unsat_path = BatList . filteri ( fun i _ -> mini <= i && i <= maxi ) path in Infeasible unsat_path | Solver . UNKNOWN -> Unknown in iter_wp ( List . rev path ) ( List . length path - 1 ) Env . empty let check_path = wp_path end
module Configuration = struct type t = { name : string ; parameters : ( string * string ) list } let to_json { name ; parameters } : Yojson . Basic . json = ` Assoc [ " name " , ` String name ; " parameters " , ` Assoc ( List . map parameters ~ f ( : fun ( a , b ) -> a , ` String b ) ) ; ] let render { parameters ; _ } = List . concat_map parameters ~ f ( : fun ( a , b ) -> [ a ; b ] ) let default = { name = " default " ; parameters = [ ] } let example_1 = { name = " examplel_1 " ; parameters = [ " - c1 " , " 20 " ; " - C1 " , " 100 " ; " - c2 " , " 20 " ; " - C2 " , " 100 " ; ] } let name t = t . name end
let run ~ run_with ~ normal ~ tumor ~ result_prefix ( ? more_edges = [ ] ) ~ configuration ( ) = let open KEDSL in let open Configuration in let name = Filename . basename result_prefix in let result_file suffix = result_prefix ^ suffix in let output_file = result_file " - somatic . vcf " in let output_prefix = " virmid - output " in let work_dir = result_file " - workdir " in let reference_fasta = Machine . get_reference_genome run_with normal # product # reference_build |> Reference_genome . fasta in let virmid_tool = Machine . get_tool run_with Machine . Tool . Default . virmid in let virmid_somatic_broken_vcf = work_dir // Filename . basename tumor # product # path ^ " . virmid . som . passed . vcf " in let processors = Machine . max_processors run_with in let make = Machine . run_big_program run_with ~ name ~ processors ~ self_ids [ " : virmid " ] Program . ( Machine . Tool . init virmid_tool && shf " mkdir - p % s " work_dir && sh ( String . concat ~ sep " : " ( [ " java - jar $ VIRMID_JAR - f " ; " - w " ; work_dir ; " - R " ; reference_fasta # product # path ; " - D " ; tumor # product # path ; " - N " ; normal # product # path ; " - t " ; Int . to_string processors ; " - o " ; output_prefix ; ] @ Configuration . render configuration ) ) && shf " sed ' s ( /\\## INFO . * Number = A , Type = String , ) \\ /\\ 1 ' / % s > % s " virmid_somatic_broken_vcf output_file ) in workflow_node ~ name ~ make ( vcf_file output_file ~ reference_build : normal # product # reference_build ~ host : Machine . ( as_host run_with ) ) ~ edges ( : more_edges @ [ depends_on normal ; depends_on tumor ; depends_on reference_fasta ; depends_on ( Machine . Tool . ensure virmid_tool ) ; ] )
module Pp_spec : sig type t val make : Preprocess . Without_instrumentation . t Preprocess . t Module_name . Per_item . t -> Ocaml_version . t -> t val pped_module : t -> Module . t -> Module . t type t = ( Module . t -> Module . t ) Module_name . Per_item . t let make preprocess v = Module_name . Per_item . map preprocess ~ f ( : fun pp -> match Preprocess . remove_future_syntax ~ for_ : Compiler pp v with | No_preprocessing -> Module . ml_source | Action ( _ , _ ) -> fun m -> Module . ml_source ( Module . pped m ) | Pps { loc = _ ; pps = _ ; flags = _ ; staged } -> if staged then Module . ml_source else fun m -> Module . pped ( Module . ml_source m ) ) let pped_module ( t : t ) m = Module_name . Per_item . get t ( Module . name m ) m end
let setup_copy_rules_for_impl ~ sctx ~ dir vimpl = let ctx = Super_context . context sctx in let vlib = Vimpl . vlib vimpl in let impl = Vimpl . impl vimpl in let impl_obj_dir = Dune_file . Library . obj_dir ~ dir impl in let vlib_obj_dir = Lib . obj_dir vlib in let add_rule = Super_context . add_rule sctx ~ dir in let copy_to_obj_dir ~ src ~ dst = add_rule ~ loc ( : Loc . of_pos __POS__ ) ( Action_builder . symlink ~ src ~ dst ) in let { Lib_config . has_native ; ext_obj ; _ } = ctx . lib_config in let { Mode . Dict . byte ; native } = Dune_file . Mode_conf . Set . eval impl . modes ~ has_native in let copy_obj_file m kind = let src = Obj_dir . Module . cm_file_exn vlib_obj_dir m ~ kind in let dst = Obj_dir . Module . cm_file_exn impl_obj_dir m ~ kind in copy_to_obj_dir ~ src ~ dst in let open Memo . O in let copy_objs src = copy_obj_file src Cmi >>> Memo . when_ ( Module . visibility src = Public && Obj_dir . need_dedicated_public_dir impl_obj_dir ) ( fun ( ) -> let dst = Obj_dir . Module . cm_public_file_exn impl_obj_dir src ~ kind : Cmi in let src = Obj_dir . Module . cm_public_file_exn vlib_obj_dir src ~ kind : Cmi in copy_to_obj_dir ~ src ~ dst ) >>> Memo . when_ ( Module . has src ~ ml_kind : Impl ) ( fun ( ) -> Memo . when_ byte ( fun ( ) -> copy_obj_file src Cmo ) >>> Memo . when_ native ( fun ( ) -> copy_obj_file src Cmx >>> let object_file dir = Obj_dir . Module . o_file_exn dir src ~ ext_obj in copy_to_obj_dir ~ src ( : object_file vlib_obj_dir ) ~ dst ( : object_file impl_obj_dir ) ) ) in let vlib_modules = Vimpl . vlib_modules vimpl in Modules . fold_no_vlib vlib_modules ~ init ( : Memo . return ( ) ) ~ f ( : fun m acc -> acc >>> copy_objs m )
let impl sctx ( ~ lib : Dune_file . Library . t ) ~ scope = let open Memo . O in match lib . implements with | None -> Memo . return None | Some ( loc , implements ) -> ( Lib . DB . find ( Scope . libs scope ) implements >>= function | None -> User_error . raise ~ loc [ Pp . textf " Cannot implement % s as that library isn ' t available " ( Lib_name . to_string implements ) ] | Some vlib -> let info = Lib . info vlib in let virtual_ = let virtual_ = Lib_info . virtual_ info in match virtual_ with | None -> User_error . raise ~ loc : lib . buildable . loc [ Pp . textf " Library % s isn ' t virtual and cannot be implemented " ( Lib_name . to_string implements ) ] | Some v -> v in let + vlib_modules , vlib_foreign_objects = let foreign_objects = Lib_info . foreign_objects info in match ( virtual_ , foreign_objects ) with | External _ , Local | Local , External _ -> assert false | External modules , External fa -> Memo . return ( modules , fa ) | Local , Local -> let name = Lib . name vlib in let vlib = Lib . Local . of_lib_exn vlib in let * dir_contents = let info = Lib . Local . info vlib in let dir = Lib_info . src_dir info in Dir_contents . get sctx ~ dir in let * preprocess = Resolve . Memo . read_memo ( Preprocess . Per_module . with_instrumentation lib . buildable . preprocess ~ instrumentation_backend : ( Lib . DB . instrumentation_backend ( Scope . libs scope ) ) ) in let * modules = let pp_spec = Pp_spec . make preprocess ( Super_context . context sctx ) . version in Dir_contents . ocaml dir_contents >>| Ml_sources . modules ~ for_ ( : Library name ) >>= Modules . map_user_written ~ f ( : fun m -> Memo . return ( Pp_spec . pped_module pp_spec m ) ) in let + foreign_objects = let ext_obj = ( Super_context . context sctx ) . lib_config . ext_obj in let dir = Obj_dir . obj_dir ( Lib . Local . obj_dir vlib ) in let + foreign_sources = Dir_contents . foreign_sources dir_contents in foreign_sources |> Foreign_sources . for_lib ~ name |> Foreign . Sources . object_files ~ ext_obj ~ dir |> List . map ~ f : Path . build in ( modules , foreign_objects ) in Some ( Vimpl . make ~ impl : lib ~ vlib ~ vlib_modules ~ vlib_foreign_objects ) )
type t = | Public | Private
let to_string = function | Public -> " public " | Private -> " private "
let to_dyn t = Dyn . string ( to_string t )
let encode = let open Dune_lang . Encoder in function | Public -> string " public " | Private -> string " private "
let decode = let open Dune_lang . Decoder in plain_string ( fun ~ loc -> function | " public " -> Public | " private " -> Private | _ -> User_error . raise ~ loc [ Pp . text " Not a valid visibility . Valid visibility is public or private " ] )
let is_public = function | Public -> true | Private -> false
let is_private t = not ( is_public t )
module Map = struct type ' a t = { public : ' a ; private_ : ' a } let make_both a = { public = a ; private_ = a } let find { private_ ; public } = function | Private -> private_ | Public -> public end
module Bounds = struct type t = { min_x : int ; min_y : int ; max_x : int ; max_y : int } [ @@ deriving sexp , equal ] end
let get_conservative_vis_bounds ( element : Dom_html . element Js . t ) : Bounds . t option = let client_bounds = element ## getBoundingClientRect in let client_x = client_bounds . ## left and client_y = client_bounds . ## top and client_bottom = client_bounds . ## bottom and client_right = client_bounds . ## right and client_width = client_bounds . ## width and client_height = client_bounds . ## height and window_height = Dom_html . window . ## innerHeight and window_width = Dom_html . window . ## innerWidth in let % bind . Option window_height = Js . Optdef . to_option window_height in let % bind . Option window_width = Js . Optdef . to_option window_width in let window_height = Float . of_int window_height and window_width = Float . of_int window_width and client_width = Js . Optdef . get client_width ( Fn . const 0 . 0 ) and client_height = Js . Optdef . get client_height ( Fn . const 0 . 0 ) in if Float . O . ( client_y > window_height || client_x > window_width || client_bottom < 0 . 0 || client_right < 0 . 0 ) then None else let open Float in let min_y = max 0 . 0 ( - client_y ) and min_x = max 0 . 0 ( - client_x ) and max_y = if client_bottom < window_height then client_height else window_height - client_y and max_x = if client_right < window_width then client_width else window_width - client_x in Some { Bounds . min_x = iround_down_exn min_x ; min_y = iround_down_exn min_y ; max_x = iround_up_exn max_x ; max_y = iround_up_exn max_y } ; ;
module T = struct module Input = struct type t = Bounds . t -> unit Vdom . Effect . t [ @@ deriving sexp_of ] let combine left right bounds = Vdom . Effect . sequence_as_sibling ( left bounds ) ~ unless_stopped ( : fun ( ) -> right bounds ) ; ; end module State = struct type t = { mutable callback : Bounds . t -> unit ; mutable prev : Bounds . t ; mutable animation_id : ( Dom_html . animation_frame_request_id [ @ sexp . opaque ] ) ; mutable dirty : bool } [ @@ deriving sexp_of ] let schedule state ~ f = cancel_animation_frame state . animation_id ; state . animation_id <- request_animation_frame f ; ; end let wrap_with_handle f t = Vdom . Effect . Expert . handle_non_dom_event_exn ( f t ) let init callback element = let state = { State . callback = wrap_with_handle callback ; prev = { min_x = 0 ; min_y = 0 ; max_x = 0 ; max_y = 0 } ; animation_id = request_animation_frame ( Fn . const ( ) ) ; dirty = true } in let rec every_frame _frame_time = ( match get_conservative_vis_bounds element with | Some bounds when state . dirty || not ( Bounds . equal bounds state . prev ) -> state . callback bounds ; state . prev <- bounds ; state . dirty <- false | _ -> ( ) ) ; State . schedule state ~ f : every_frame in State . schedule state ~ f : every_frame ; state ; ; let on_mount _input _state _element = ( ) let update ~ old_input : _ ~ new_input : callback ( state : State . t ) _element = state . dirty <- true ; state . callback <- wrap_with_handle callback ; ; let destroy _input ( state : State . t ) _element = cancel_animation_frame state . animation_id ; ; end
module Hook = Vdom . Attr . Hooks . Make ( T )
let on_change f = Vdom . Attr . create_hook " bounds - change " ( Hook . create f )
type node = | Expression of Expression . t | Statement of Statement . t | Argument of Identifier . t Node . t | Parameter of Parameter . t | Reference of Reference . t Node . t | Substring of Substring . t | Generator of Comprehension . Generator . t
module type NodeVisitor = sig type t val node : t -> node -> t val visit_statement_children : t -> Statement . t -> bool val visit_format_string_children : t -> Expression . t -> bool end
module MakeNodeVisitor ( Visitor : NodeVisitor ) = struct let visit_node ~ state ~ visitor node = state := visitor ! state node let visit_argument { Call . Argument . value ; _ } ~ visit_expression = visit_expression value let visit_parameter ( { Node . value = { Parameter . value ; annotation ; _ } ; _ } as parameter ) ~ visitor ~ visit_expression ~ state = visit_node ~ state ~ visitor ( Parameter parameter ) ; Option . iter ~ f : visit_expression value ; Option . iter ~ f : visit_expression annotation let rec visit_expression ~ state ? visitor_override expression = let visitor = Option . value visitor_override ~ default : Visitor . node in let visit_expression = visit_expression ~ state ? visitor_override in let visit_generator ( { Comprehension . Generator . target ; iterator ; conditions ; _ } as generator ) ~ visit_expression = visit_node ~ state ~ visitor ( Generator generator ) ; visit_expression target ; visit_expression iterator ; List . iter conditions ~ f : visit_expression in let visit_entry { Dictionary . Entry . key ; value } ~ visit_expression = visit_expression key ; visit_expression value in let visit_children value = match value with | Expression . Await expression -> visit_expression expression | BooleanOperator { BooleanOperator . left ; right ; _ } | ComparisonOperator { ComparisonOperator . left ; right ; _ } -> visit_expression left ; visit_expression right | Call { Call . callee ; arguments } -> visit_expression callee ; let visit_argument { Call . Argument . value ; name } = name >>| ( fun name -> visit_node ~ state ~ visitor ( Argument name ) ) |> ignore ; visit_expression value in List . iter arguments ~ f : visit_argument | Dictionary { Dictionary . entries ; keywords } -> List . iter entries ~ f ( : visit_entry ~ visit_expression ) ; List . iter keywords ~ f : visit_expression |> ignore | DictionaryComprehension { Comprehension . element ; generators } -> List . iter generators ~ f ( : visit_generator ~ visit_expression ) ; visit_entry element ~ visit_expression | Generator { Comprehension . element ; generators } -> List . iter generators ~ f ( : visit_generator ~ visit_expression ) ; visit_expression element | Lambda { Lambda . parameters ; body } -> List . iter parameters ~ f ( : visit_parameter ~ state ~ visitor ~ visit_expression ) ; visit_expression body | List elements -> List . iter elements ~ f : visit_expression | ListComprehension { Comprehension . element ; generators } -> List . iter generators ~ f ( : visit_generator ~ visit_expression ) ; visit_expression element | Name ( Name . Identifier _ ) -> ( ) | Name ( Name . Attribute { base ; _ } ) -> visit_expression base | Set elements -> List . iter elements ~ f : visit_expression | SetComprehension { Comprehension . element ; generators } -> List . iter generators ~ f ( : visit_generator ~ visit_expression ) ; visit_expression element | Starred starred -> ( match starred with | Starred . Once expression | Starred . Twice expression -> visit_expression expression ) | FormatString substrings -> List . iter ~ f ( : fun substring -> visit_node ~ state ~ visitor ( Substring substring ) ) substrings ; if Visitor . visit_format_string_children ! state expression then let visit_children = function | Substring . Format expression -> visit_expression expression | _ -> ( ) in List . iter ~ f : visit_children substrings | Ternary { Ternary . target ; test ; alternative } -> visit_expression target ; visit_expression test ; visit_expression alternative | Tuple elements -> List . iter elements ~ f : visit_expression | UnaryOperator { UnaryOperator . operand ; _ } -> visit_expression operand | WalrusOperator { target ; value } -> visit_expression target ; visit_expression value | Expression . Yield expression -> Option . iter ~ f : visit_expression expression | Expression . YieldFrom expression -> visit_expression expression | Constant _ -> ( ) in visit_children ( Node . value expression ) ; visit_node ~ state ~ visitor ( Expression expression ) let rec visit_statement ~ state statement = let location = Node . location statement in let visitor = Visitor . node in let visit_expression = visit_expression ~ state in let visit_statement = visit_statement ~ state in let visit_children value = match value with | Statement . Assign { Assign . target ; annotation ; value ; _ } -> visit_expression target ; Option . iter ~ f : visit_expression annotation ; visit_expression value | Assert { Assert . test ; message ; _ } -> visit_expression test ; Option . iter ~ f : visit_expression message | Class ( { Class . name ; base_arguments ; body ; decorators ; _ } as class_ ) -> visit_node ~ state ~ visitor ( Reference ( Node . create ~ location ( : Class . name_location ~ body_location : location class_ ) name ) ) ; List . iter base_arguments ~ f ( : visit_argument ~ visit_expression ) ; List . iter body ~ f : visit_statement ; List . iter ~ f : visit_expression decorators | Define ( { Define . signature ; captures ; body ; unbound_names = _ } as define ) -> let iter_signature { Define . Signature . name ; parameters ; decorators ; return_annotation ; _ } = visit_node ~ state ~ visitor ( Reference ( Node . create ~ location ( : Define . name_location ~ body_location : location define ) name ) ) ; List . iter parameters ~ f ( : visit_parameter ~ state ~ visitor ~ visit_expression ) ; List . iter ~ f : visit_expression decorators ; Option . iter ~ f : visit_expression return_annotation in let iter_capture { Define . Capture . kind ; _ } = match kind with | Define . Capture . Kind . Annotation annotation -> Option . iter annotation ~ f : visit_expression | Define . Capture . Kind . DefineSignature value -> iter_signature value | Define . Capture . Kind . ( Self _ | ClassSelf _ ) -> ( ) in iter_signature signature ; List . iter body ~ f : visit_statement ; List . iter captures ~ f : iter_capture | Delete expressions -> List . iter expressions ~ f : visit_expression | Expression expression -> visit_expression expression | For { For . target ; iterator ; body ; orelse ; _ } -> visit_expression target ; visit_expression iterator ; List . iter body ~ f : visit_statement ; List . iter orelse ~ f : visit_statement | If { If . test ; body ; orelse } -> visit_expression test ; List . iter body ~ f : visit_statement ; List . iter orelse ~ f : visit_statement | Match { Match . subject ; cases } -> let rec visit_pattern { Node . value ; location } = match value with | Match . Pattern . MatchAs { pattern ; _ } -> Option . iter pattern ~ f : visit_pattern | MatchClass { patterns ; keyword_patterns ; _ } -> List . iter patterns ~ f : visit_pattern ; List . iter keyword_patterns ~ f : visit_pattern | MatchMapping { keys ; patterns ; _ } -> List . iter keys ~ f : visit_expression ; List . iter patterns ~ f : visit_pattern | MatchOr patterns | MatchSequence patterns -> List . iter patterns ~ f : visit_pattern | MatchSingleton constant -> visit_expression { Node . value = Expression . Constant constant ; location } | MatchValue expression -> visit_expression expression | MatchStar _ | MatchWildcard -> ( ) in let visit_case { Match . Case . pattern ; guard ; body } = visit_pattern pattern ; Option . iter guard ~ f : visit_expression ; List . iter body ~ f : visit_statement in visit_expression subject ; List . iter cases ~ f : visit_case | Raise { Raise . expression ; from } -> Option . iter ~ f : visit_expression expression ; Option . iter ~ f : visit_expression from | Return { Return . expression ; _ } -> Option . iter ~ f : visit_expression expression | Try { Try . body ; handlers ; orelse ; finally } -> let visit_handler { Try . Handler . kind ; body ; _ } = Option . iter ~ f : visit_expression kind ; List . iter body ~ f : visit_statement in List . iter body ~ f : visit_statement ; List . iter handlers ~ f : visit_handler ; List . iter orelse ~ f : visit_statement ; List . iter finally ~ f : visit_statement | With { With . items ; body ; _ } -> let visit_item ( item , alias ) = visit_expression item ; Option . iter ~ f : visit_expression alias in List . iter items ~ f : visit_item ; List . iter body ~ f : visit_statement | While { While . test ; body ; orelse } -> visit_expression test ; List . iter body ~ f : visit_statement ; List . iter orelse ~ f : visit_statement | Import _ | Nonlocal _ | Global _ | Pass | Continue | Break -> ( ) in if Visitor . visit_statement_children ! state statement then visit_children ( Node . value statement ) ; visit_node ~ state ~ visitor ( Statement statement ) let visit state source = let state = ref state in List . iter source . Source . statements ~ f ( : visit_statement ~ state ) ; ! state end
module type Visitor = sig type t val expression : t -> Expression . t -> t val statement : t -> Statement . t -> t end
module Make ( Visitor : Visitor ) = struct let visit = let module NodeVisitor = MakeNodeVisitor ( struct type t = Visitor . t let node state = function | Expression expression -> Visitor . expression state expression | Statement statement -> Visitor . statement state statement | _ -> state let visit_statement_children _ _ = true let visit_format_string_children _ _ = false end ) in NodeVisitor . visit end
module type StatementVisitor = sig type t val visit_children : Statement . t -> bool val statement : Source . t -> t -> Statement . t -> t end
module MakeStatementVisitor ( Visitor : StatementVisitor ) = struct let visit state ( { Source . statements ; _ } as source ) = let state = ref state in let open Statement in let rec visit_statement { Node . location ; value } = if Visitor . visit_children { Node . location ; value } then ( match value with | Assign _ | Assert _ | Break | Continue | Delete _ | Expression _ | Global _ | Import _ | Pass | Raise _ | Return _ | Nonlocal _ -> ( ) | Class { Class . body ; _ } | Define { Define . body ; _ } | With { With . body ; _ } -> List . iter ~ f : visit_statement body | For { For . body ; orelse ; _ } | If { If . body ; orelse ; _ } | While { While . body ; orelse ; _ } -> List . iter ~ f : visit_statement body ; List . iter ~ f : visit_statement orelse | Match { Match . cases ; _ } -> let visit_case { Match . Case . body ; _ } = List . iter ~ f : visit_statement body in List . iter ~ f : visit_case cases | Try { Try . body ; handlers ; orelse ; finally } -> let visit_handler { Try . Handler . body ; _ } = List . iter ~ f : visit_statement body in List . iter ~ f : visit_statement body ; List . iter ~ f : visit_handler handlers ; List . iter ~ f : visit_statement orelse ; List . iter ~ f : visit_statement finally ) else ( ) ; state := Visitor . statement source ! state { Node . location ; value } in List . iter ~ f : visit_statement statements ; ! state end
module type ExpressionPredicate = sig type t val predicate : Expression . t -> t option end
module type StatementPredicate = sig type t val visit_children : Statement . t -> bool val predicate : Statement . t -> t option end
module type NodePredicate = sig type t val predicate : node -> t option end
module Collector ( ExpressionPredicate : ExpressionPredicate ) ( StatementPredicate : StatementPredicate ) ( NodePredicate : NodePredicate ) = struct type collection = { expressions : ExpressionPredicate . t list ; statements : StatementPredicate . t list ; nodes : NodePredicate . t list ; } let collect source = let module CollectingVisitor = struct type t = collection let expression ( { expressions ; _ } as state ) expression = match ExpressionPredicate . predicate expression with | Some result -> { state with expressions = result :: expressions } | None -> state let statement ( { statements ; _ } as state ) statement = match StatementPredicate . predicate statement with | Some result -> { state with statements = result :: statements } | None -> state let node ( { nodes ; _ } as state ) node = let state = match node with | Expression expression_node -> expression state expression_node | Statement statement_node -> statement state statement_node | _ -> state in match NodePredicate . predicate node with | Some result -> { state with nodes = result :: nodes } | None -> state let visit_statement_children _ _ = true let visit_format_string_children _ _ = false end in let module CollectingVisit = MakeNodeVisitor ( CollectingVisitor ) in CollectingVisit . visit { expressions = [ ] ; statements = [ ] ; nodes = [ ] } source end
module UnitPredicate = struct type t = unit let visit_children _ = true let predicate _ = None end
module ExpressionCollector ( Predicate : ExpressionPredicate ) = struct let collect source = let module Collector = Collector ( Predicate ) ( UnitPredicate ) ( UnitPredicate ) in let { Collector . expressions ; _ } = Collector . collect source in expressions end
module StatementCollector ( Predicate : StatementPredicate ) = struct module CollectingVisit = MakeStatementVisitor ( struct type t = Predicate . t list let visit_children = Predicate . visit_children let statement _ statements statement = match Predicate . predicate statement with | Some result -> result :: statements | None -> statements end ) let collect source = CollectingVisit . visit [ ] source end
module NodeCollector ( Predicate : NodePredicate ) = struct let collect source = let module Collector = Collector ( UnitPredicate ) ( UnitPredicate ) ( Predicate ) in let { Collector . nodes ; _ } = Collector . collect source in nodes end
let collect_locations source = let module Collector = Collector ( UnitPredicate ) ( UnitPredicate ) ( struct type t = Location . t let predicate = function | Expression node -> Some ( Node . location node ) | Statement node -> Some ( Node . location node ) | Argument node -> Some ( Node . location node ) | Parameter node -> Some ( Node . location node ) | Reference node -> Some ( Node . location node ) | Substring ( Substring . Format node ) -> Some ( Node . location node ) | Substring _ | Generator _ -> None end ) in let { Collector . nodes ; _ } = Collector . collect source in nodes
let collect_calls statement = let open Expression in let module Collector = ExpressionCollector ( struct type t = Call . t Node . t let predicate expression = match expression with | { Node . location ; value = Call call } -> Some { Node . location ; value = call } | _ -> None end ) in Collector . collect ( Source . create [ statement ] )
let collect_names ( ? only_simple = false ) statement = let open Expression in let module Collector = ExpressionCollector ( struct type t = Name . t Node . t let predicate expression = match expression with | { Node . location ; value = Name name } -> if only_simple && not ( is_simple_name name ) then None else Some { Node . location ; value = name } | _ -> None end ) in Collector . collect ( Source . create [ statement ] )
let collect_calls_and_names statement = let open Expression in let module Collector = ExpressionCollector ( struct type t = Expression . t let predicate expression = match expression with | { Node . value = Call _ ; _ } -> Some expression | { Node . value = Name _ ; _ } -> Some expression | _ -> None end ) in Collector . collect ( Source . create [ statement ] )
let collect_base_identifiers statement = let open Expression in let module Collector = ExpressionCollector ( struct type t = Identifier . t Node . t let predicate expression = match expression with | { Node . location ; value = Name ( Name . Identifier identifier ) } -> Some { Node . location ; value = identifier } | _ -> None end ) in Collector . collect ( Source . create [ statement ] )
let rec collect_non_generic_type_names { Node . value ; _ } = match value with | Expression . Call { Call . arguments ; _ } -> List . concat_map ~ f ( : fun { Call . Argument . value ; _ } -> collect_non_generic_type_names value ) arguments | Tuple elements | List elements -> List . concat_map ~ f : collect_non_generic_type_names elements | Name name -> name_to_reference name >>| Reference . show |> Option . to_list | _ -> [ ]
let collect_format_strings_with_ignores ~ ignore_line_map source = let module CollectIgnoredFormatStrings = ExpressionCollector ( struct type t = Expression . t * Ignore . t list let predicate = function | { Node . value = Expression . FormatString _ ; location } as expression -> Map . find ignore_line_map ( Location . line location ) >>| fun ignores -> expression , ignores | _ -> None end ) in CollectIgnoredFormatStrings . collect source
let test_collect _ = let assert_collect statements expected = let collect = let module ExpressionPredicate = struct type t = Expression . t let predicate expression = Some expression end in let module StatementPredicate = struct type t = Statement . t let visit_children _ = true let predicate statement = Some statement end in let module NodePredicate = struct type t = Visit . node let predicate node = Some node end in let module Collector = Visit . Collector ( ExpressionPredicate ) ( StatementPredicate ) ( NodePredicate ) in let { Collector . expressions ; statements ; _ } = Collector . collect ( Source . create statements ) in expressions , statements in let equal left right = List . equal [ % compare . equal : Expression . t ] ( fst left ) ( fst right ) && List . equal [ % compare . equal : Statement . t ] ( snd left ) ( snd right ) in let printer ( expressions , statements ) = Format . asprintf " % a | % a " Sexp . pp [ % message ( expressions : Expression . t list ) ] Sexp . pp [ % message ( statements : Statement . t list ) ] in assert_equal ~ cmp : equal ~ printer expected collect in assert_collect [ + Statement . Expression ( + Expression . Constant ( Constant . Float 1 . 0 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Float 2 . 0 ) ) ; ] ( [ + Expression . Constant ( Constant . Float 2 . 0 ) ; + Expression . Constant ( Constant . Float 1 . 0 ) ] , [ + Statement . Expression ( + Expression . Constant ( Constant . Float 2 . 0 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Float 1 . 0 ) ) ; ] ) ; assert_collect [ + Statement . If { If . test = + Expression . Constant ( Constant . Float 2 . 0 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Float 3 . 0 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Float 4 . 0 ) ) ] ; } ; ] ( [ + Expression . Constant ( Constant . Float 4 . 0 ) ; + Expression . Constant ( Constant . Float 3 . 0 ) ; + Expression . Constant ( Constant . Float 2 . 0 ) ; ] , [ + Statement . If { If . test = + Expression . Constant ( Constant . Float 2 . 0 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Float 3 . 0 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Float 4 . 0 ) ) ] ; } ; + Statement . Expression ( + Expression . Constant ( Constant . Float 4 . 0 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Float 3 . 0 ) ) ; ] ) ; assert_collect [ + Statement . If { If . test = + Expression . Constant ( Constant . Float 1 . 0 ) ; body = [ + Statement . If { If . test = + Expression . Constant ( Constant . Float 2 . 0 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Float 3 . 0 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Float 4 . 0 ) ) ] ; } ; ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Float 5 . 0 ) ) ] ; } ; ] ( [ + Expression . Constant ( Constant . Float 5 . 0 ) ; + Expression . Constant ( Constant . Float 4 . 0 ) ; + Expression . Constant ( Constant . Float 3 . 0 ) ; + Expression . Constant ( Constant . Float 2 . 0 ) ; + Expression . Constant ( Constant . Float 1 . 0 ) ; ] , [ + Statement . If { If . test = + Expression . Constant ( Constant . Float 1 . 0 ) ; body = [ + Statement . If { If . test = + Expression . Constant ( Constant . Float 2 . 0 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Float 3 . 0 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Float 4 . 0 ) ) ] ; } ; ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Float 5 . 0 ) ) ] ; } ; + Statement . Expression ( + Expression . Constant ( Constant . Float 5 . 0 ) ) ; + Statement . If { If . test = + Expression . Constant ( Constant . Float 2 . 0 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Float 3 . 0 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Float 4 . 0 ) ) ] ; } ; + Statement . Expression ( + Expression . Constant ( Constant . Float 4 . 0 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Float 3 . 0 ) ) ; ] ) ; assert_collect [ + Statement . Match { Match . subject = + Expression . Constant ( Constant . Integer 0 ) ; cases = [ { Match . Case . pattern = + Match . Pattern . MatchSingleton ( Constant . Integer 2 ) ; guard = Some ( + Expression . Constant ( Constant . Integer 4 ) ) ; body = [ ] ; } ; ] ; } ; ] ( [ + Expression . Constant ( Constant . Integer 4 ) ; + Expression . Constant ( Constant . Integer 2 ) ; + Expression . Constant ( Constant . Integer 0 ) ; ] , [ + Statement . Match { Match . subject = + Expression . Constant ( Constant . Integer 0 ) ; cases = [ { Match . Case . pattern = + Match . Pattern . MatchSingleton ( Constant . Integer 2 ) ; guard = Some ( + Expression . Constant ( Constant . Integer 4 ) ) ; body = [ ] ; } ; ] ; } ; ] ) ; assert_collect [ + Statement . Expression ( + Expression . WalrusOperator { target = " ! a " ; value = + Expression . Constant ( Constant . Integer 1 ) } ) ; ] ( [ + Expression . WalrusOperator { target = " ! a " ; value = + Expression . Constant ( Constant . Integer 1 ) } ; + Expression . Constant ( Constant . Integer 1 ) ; + Expression . Name ( Identifier " a " ) ; ] , [ + Statement . Expression ( + Expression . WalrusOperator { target = " ! a " ; value = + Expression . Constant ( Constant . Integer 1 ) } ) ; ] )
let test_collect_location _ = let assert_collect_location source expected_locations = let source = parse ~ handle " : test . py " source in let actual_locations = Visit . collect_locations source in let expected_locations = let create_location ( start_line , start_column , end_line , end_column ) = { Location . start = { Ast . Location . line = start_line ; column = start_column } ; stop = { Ast . Location . line = end_line ; column = end_column } ; } in List . map ~ f : create_location expected_locations in let equal left right = List . equal Location . equal left right in let printer locations = Format . asprintf " % a " Sexp . pp [ % message ( locations : Location . t list ) ] in assert_equal ~ cmp : equal ~ printer expected_locations actual_locations in assert_collect_location { | if test : 1 else : 2 } | [ 2 , 0 , 5 , 3 ; 5 , 2 , 5 , 3 ; 5 , 2 , 5 , 3 ; 3 , 2 , 3 , 3 ; 3 , 2 , 3 , 3 ; 2 , 3 , 2 , 7 ; ]
let test_collect_non_generic_type_names _ = let assert_non_generic_type_names expression expected = assert_equal ~ cmp [ :% equal : string list ] ~ printer [ :% show : string list ] expected ( Visit . collect_non_generic_type_names ( parse_single_expression ~ preprocess : true expression ) ) in assert_non_generic_type_names " typing . Tuple " [ " typing . Tuple " ] ; assert_non_generic_type_names " typing . Tuple [ int ] " [ " int " ] ; assert_non_generic_type_names " typing . Mapping [ str , typing . Any ] " [ " str " ; " typing . Any " ] ; assert_non_generic_type_names " typing . Literal [ ' typing . Any ' ] " [ ] ; assert_non_generic_type_names " typing . Callable [ [ int ] , str ] " [ " int " ; " str " ] ; assert_non_generic_type_names " typing . Union [ typing . Callable [ [ int ] , str ] ] " [ " int " ; " str " ] ; assert_non_generic_type_names " typing . Union [ typing . Tuple ] " [ " typing . Tuple " ] ; ( )
let test_collect_format_strings_with_ignores _ = let assert_format_strings_with_ignores source expected = let ( { Source . typecheck_flags = { ignore_lines ; _ } ; _ } as source ) = parse source in let ignore_line_map = List . map ignore_lines ~ f ( : fun ( { Ignore . ignored_line ; _ } as ignore ) -> ignored_line , ignore ) |> Int . Map . of_alist_multi in let format_strings_with_ignores = Visit . collect_format_strings_with_ignores ~ ignore_line_map source |> List . map ~ f : snd |> List . map ~ f : ( List . map ~ f ( : fun { Ignore . codes ; ignored_line ; kind ; _ } -> ignored_line , kind , codes ) ) in assert_equal ~ cmp [ :% compare . equal : ( int * Ignore . kind * int list ) list list ] ~ printer [ :% show : ( int * Ignore . kind * int list ) list list ] expected format_strings_with_ignores in let open Ignore in assert_format_strings_with_ignores { | def foo ( ) -> None : # pyre - ignore [ 7 ] # pyre - fixme [ 58 , 42 ] # Some comment . f " " " foo bar { 1 + " hello " } baz " " " } | [ [ 6 , PyreIgnore , [ 7 ] ; 6 , PyreFixme , [ 58 ; 42 ] ] ] ; assert_format_strings_with_ignores { | def foo ( ) -> None : # pyre - fixme [ 58 ] # Some comment . f " " " { 1 + " hello2 " } " " " f " " " { 1 + " hello3 " } " " " f " " " { 1 + " hello4 " } " " " } | [ [ 5 , PyreFixme , [ 58 ] ] ] ; assert_format_strings_with_ignores { | def foo ( ) -> None : # type : ignore f " { 1 + ' hello ' } " # pyre - fixme [ 58 ] f " { 1 + ' hello ' } " } | [ [ 7 , PyreFixme , [ 58 ] ] ; [ 4 , TypeIgnore , [ ] ] ] ; assert_format_strings_with_ignores { | def foo ( ) -> None : # Unignored format string f " " " { 1 + " world " } " " " } | [ ] ; ( )
let test_node_visitor _ = let module Visitor = struct type t = int String . Table . t let node state node = let increment hash_table key = match Hashtbl . find hash_table key with | None -> Hashtbl . set hash_table ~ key ~ data : 1 | Some value -> Hashtbl . set hash_table ~ key ~ data ( : value + 1 ) in match node with | Visit . Expression _ -> increment state " expression " ; state | Visit . Statement _ -> increment state " statement " ; state | Visit . Argument _ -> increment state " identifier " ; state | Visit . Parameter _ -> increment state " parameter " ; state | Visit . Reference _ -> increment state " reference " ; state | Visit . Substring _ -> increment state " substring " ; state | Visit . Generator _ -> increment state " generator " ; state let visit_statement_children _ _ = true let visit_format_string_children _ _ = true end in let module Visit = Visit . MakeNodeVisitor ( Visitor ) in let assert_counts source expected_counts = let table = Visit . visit ( String . Table . create ( ) ) source in List . iter ~ f ( : fun ( key , expected_value ) -> assert_equal ~ printer ( : fun value -> Format . sprintf " % s -> % d " key ( Option . value value ~ default : 0 ) ) ( Some expected_value ) ( Hashtbl . find table key ) ) expected_counts in let source = parse { | def foo ( x : int ) -> int : return x foo ( x = 1 ) foo ( x = 2 ) } | in assert_counts source [ " expression " , 9 ; " statement " , 4 ; " parameter " , 1 ; " identifier " , 2 ; " reference " , 1 ] ; let source = parse { | f " foo " f ' foobar ' } | in assert_counts source [ " expression " , 2 ; " statement " , 2 ; " substring " , 2 ] ; let source = parse { | f " foo { bar } " } | in assert_counts source [ " expression " , 2 ; " substring " , 2 ] ; let source = parse { | class C : x = 1 } | in assert_counts source [ " expression " , 2 ; " reference " , 1 ] ; ( )
let test_statement_visitor _ = let module StatementVisitor = struct type t = int String . Table . t let visit_children _ = true let statement _ visited statement = let increment hash_table key = match Hashtbl . find hash_table key with | None -> Hashtbl . set hash_table ~ key ~ data : 1 | Some value -> Hashtbl . set hash_table ~ key ~ data ( : value + 1 ) in match Node . value statement with | Statement . Assign _ -> increment visited " assign " ; visited | Import _ -> increment visited " import " ; visited | Match _ -> increment visited " match " ; visited | Return _ -> increment visited " return " ; visited | _ -> visited end in let module Visit = Visit . MakeStatementVisitor ( StatementVisitor ) in let assert_counts source expected_counts = let table = Visit . visit ( String . Table . create ( ) ) source in List . iter ~ f ( : fun ( key , expected_value ) -> assert_equal ( Some expected_value ) ( Hashtbl . find table key ) ) expected_counts in let source = parse { | from b import c def f ( ) : a = 1 return b = 2 if x < 3 : import a c = 3 match x : case _ : import b } | in assert_counts source [ " assign " , 3 ; " return " , 1 ; " import " , 3 ; " match " , 1 ] ; ( )
let test_statement_visitor_source _ = let module StatementVisitor = struct type t = string let visit_children _ = true let statement { Source . source_path = { ModulePath . relative ; _ } ; _ } _ _ = relative end in let module Visit = Visit . MakeStatementVisitor ( StatementVisitor ) in let handle = Visit . visit " " ( parse ~ handle " : test . py " " a = 1 " ) in assert_equal " test . py " handle ; let handle = Visit . visit " " ( parse ~ handle " : test2 . py " " b = 2 " ) in assert_equal " test2 . py " handle ; ( )
let ( ) = " visit " >::: [ " collect " >:: test_collect ; " collect_location " >:: test_collect_location ; " collect_non_generic_type_names " >:: test_collect_non_generic_type_names ; " collect_format_strings_with_ignores " >:: test_collect_format_strings_with_ignores ; " node_visitor " >:: test_node_visitor ; " statement_visitor " >:: test_statement_visitor ; " statement_visitor_source " >:: test_statement_visitor_source ; ] |> Test . run
let gauss a b x = let xb = Vec . sub x b in . ~- ( exp ( dot xb ( symv a xb ) . / 2 . 0 ) )
let dgauss a b x = symv ~ alpha ( : gauss a b x ) a ( Vec . sub x b )
let gnuplot f = let oc = Unix . open_process_out " gnuplot " in let ppf = formatter_of_out_channel oc in f ppf ; pp_print_flush ppf ( ) ; print_endline " Press Enter to exit gnuplot " ; ignore ( read_line ( ) ) ; ignore ( Unix . close_process_out oc )
let splot_fun ( ? option = " " ) ( ? n = 10 ) ( ? x1 = - 10 . 0 ) ( ? x2 = 10 . 0 ) ( ? y1 = - 10 . 0 ) ( ? y2 = 10 . 0 ) ppf f = let cx = ( x2 . - x1 ) . / float n in let cy = ( y2 . - y1 ) . / float n in fprintf ppf " splot ' ' - % s @\ n " option ; for i = 0 to n do for j = 0 to n do let x = cx . * float i . + x1 in let y = cy . * float j . + y1 in let z = f [ % vec [ x ; y ] ] in fprintf ppf " % g % g % g @\ n " x y z ; done ; fprintf ppf " @\ n " done ; fprintf ppf " end @\ n "
let steepest_descent ppf ~ loops ~ eta df f x = fprintf ppf " splot ' ' - with linespoints linetype 2 title ' ' @\ n \ % a 0 @\ n " pp_rfvec x ; for i = 1 to loops do axpy ~ alpha ( . :~- eta ) ( df x ) x ; fprintf ppf " % a 0 @\ n " pp_rfvec x done ; fprintf ppf " end @\ n "
let ( ) = let a = [ % mat [ - 0 . 1 , 0 . 1 ; 0 . 1 , - 0 . 2 ] ] in let b = [ % vec [ 1 . 0 ; 3 . 0 ] ] in let ( x1 , x2 , y1 , y2 ) = ( - 2 . 0 , 3 . 0 , 0 . 0 , 5 . 0 ) in gnuplot ( fun ppf -> fprintf ppf " set multiplot @\ n \ set view 0 , 0 # Fix a view @\ n \ unset ztics # Don ' t show ztics @\ n \ unset clabel # Don ' t show contour labels @\ n \ set ticslevel 0 @\ n \ set xrange [ % g :% g ] @\ n \ set yrange [ % g :% g ] @\ n " x1 x2 y1 y2 ; steepest_descent ppf ~ loops : 100 ~ eta : 2 . 0 ( dgauss a b ) ( gauss a b ) [ % vec [ 0 . 0 ; 1 . 0 ] ] ; fprintf ppf " set contour # Plot contour @\ n \ unset xtics # Don ' t show xtics twice @\ n \ unset ytics # Don ' t show xtics twice @\ n \ unset surface # Don ' t show a 3D surface @\ n \ set cntrparam levels 15 # Levels of contour @\ n " ; splot_fun ppf ( gauss a b ) ~ n : 50 ~ x1 ~ x2 ~ y1 ~ y2 ~ option " : w l lt 1 title ' ' " )
module type core = sig type t val t : t Ctypes . typ val ctype : t Ctypes . typ val null : t val ctype_opt : t option Ctypes . typ val pp : Format . formatter -> t -> unit val array : t list -> t Ctypes . CArray . t val array_opt : t list -> t option Ctypes . CArray . t end
module type S = sig include core val to_ptr : t -> nativeint val unsafe_from_ptr : nativeint -> t end
module type S_non_dispatchable = sig include core val to_int64 : t -> int64 val unsafe_from_int64 : int64 -> t end
module Make ( ) : S = struct type self type t = self Ctypes . structure Ctypes . ptr let t : t Ctypes . typ = Ctypes . ptr ( Ctypes . structure " " ) let ctype = t let null = Ctypes . ( coerce @@ ptr void ) t Ctypes . null let ctype_opt = let read v = if v = null then None else Some v in let write = function | None -> null | Some x -> x in Ctypes . view ~ read ~ write t let pp ppf ( x : t ) = Format . fprintf ppf " % s " @@ Nativeint . to_string @@ Ctypes . ( raw_address_of_ptr @@ coerce t ( ptr void ) x ) let array l = let a = Ctypes . CArray . of_list t l in Gc . finalise ( fun _ -> let _kept_alive = ref l in ( ) ) a ; a let array_opt l = let a = Ctypes . CArray . of_list ctype_opt ( List . map ( fun x -> Some x ) l ) in Gc . finalise ( fun _ -> let _kept_alive = ref l in ( ) ) a ; a let to_ptr x = Ctypes . raw_address_of_ptr @@ Ctypes . coerce t Ctypes . ( ptr void ) x let unsafe_from_ptr x = Ctypes . coerce Ctypes . ( ptr void ) t @@ Ctypes . ptr_of_raw_address x end
module Make_non_dispatchable ( ) : S_non_dispatchable = struct type self type t = int64 let t : t Ctypes . typ = Ctypes . int64_t let ctype = t let null = 0L let ctype_opt = let read v = if v = null then None else Some v in let write = function | None -> null | Some x -> x in Ctypes . view ~ read ~ write t let pp ppf ( x : t ) = Format . fprintf ppf " % s " @@ Nativeint . to_string @@ Ctypes . ( raw_address_of_ptr @@ coerce t ( ptr void ) x ) let array l = let a = Ctypes . CArray . of_list t l in Gc . finalise ( fun _ -> let _kept_alive = ref l in ( ) ) a ; a let array_opt l = let a = Ctypes . CArray . of_list ctype_opt ( List . map ( fun x -> Some x ) l ) in Gc . finalise ( fun _ -> let _kept_alive = ref l in ( ) ) a ; a let to_int64 x = x let unsafe_from_int64 x = x end
module type intlike = sig type t val zero : t val ctype : t Ctypes . typ end
let integer_opt ( type a ) ( module I : intlike with type t = a ) = let read x = if x = I . zero then None else Some x in let write = function None -> I . zero | Some x -> x in Ctypes . view ~ read ~ write I . ctype
let integer_opt ' zero ctype = let read x = if x = zero then None else Some x in let write = function None -> zero | Some x -> x in Ctypes . view ~ read ~ write ctype
let uint_32_t = Ctypes . view ~ read ( : U32 . to_int ) ~ write ( : U32 . of_int ) Ctypes . uint32_t
let uint_16_t = Ctypes . view ~ read ( : U16 . to_int ) ~ write ( : U16 . of_int ) Ctypes . uint16_t
module Int = struct type t = int let zero = 0 let pp = Format . pp_print_int let ctype = Ctypes . int end
module Uint_8_t = struct open U8 type t = U8 . t let ctype = Ctypes . uint8_t let zero = of_int 0 let of_int = of_int let to_int = to_int let to_string = to_string let pp ppf x = Format . pp_print_string ppf ( to_string x ) end
let bool_32 = let true ' = U32 . of_int Vk__Const . true ' and false ' = U32 . of_int Vk__Const . false ' in Ctypes . view ~ read ( : ( ) = true ' ) ~ write ( : fun x -> if x then true ' else false ' ) Ctypes . uint32_t
let bool_32_opt = let true ' = U32 . of_int Vk__Const . true ' and false ' = U32 . of_int Vk__Const . false ' in Ctypes . view ~ read ( : fun x -> if U32 . zero = x then None else if x = true ' then Some true else Some false ) ~ write ( : function None -> U32 . zero | Some x -> if x then true ' else false ' ) Ctypes . uint32_t
module Size_t_0 = struct let of_int = S . of_int let to_int = S . to_int let zero = of_int 0 let to_string = S . to_string let pp ppf x = Format . fprintf ppf " % s " ( S . to_string x ) type t = S . t let ctype = Ctypes . size_t end
module Size_t = struct include Size_t_0 let ctype_opt = integer_opt ( module Size_t_0 ) end
let size_t_opt = integer_opt ( module Size_t )
module Uint_32_t_0 = struct let zero = 0 let of_int x = x let to_int x = x let to_string = string_of_int let pp ppf x = Format . fprintf ppf " % d " x type t = int let ctype = uint_32_t end
module Uint_32_t = struct include Uint_32_t_0 let ctype_opt = integer_opt ( module Uint_32_t_0 ) end
module Uint_16_t_0 = struct let zero = 0 let of_int x = x let to_int x = x let to_string = string_of_int let pp ppf x = Format . fprintf ppf " % d " x type t = int let ctype = uint_16_t end
module Uint_16_t = struct include Uint_16_t_0 let ctype_opt = integer_opt ( module Uint_16_t_0 ) end
module Bool_32 = struct type t = bool let t = bool let ctype = bool_32 let ctype_opt = bool_32_opt let zero = true let pp = Format . pp_print_bool end
module Int_32_t = struct let zero = 0 let of_int x = x let to_int x = x let to_string = string_of_int let pp ppf x = Format . fprintf ppf " % d " x type t = int let read = Int32 . to_int let write = Int32 . of_int let ctype = Ctypes . view ~ read ~ write Ctypes . int32_t let ctype_opt = integer_opt ' zero ctype end
module Int_64_t = struct let zero = 0 let of_int x = x let to_int x = x let to_string = string_of_int let pp ppf x = Format . fprintf ppf " % d " x type t = int let read = Int64 . to_int let write = Int64 . of_int let ctype = Ctypes . view ~ read ~ write Ctypes . int64_t let ctype_opt = integer_opt ' zero ctype end
module Uint_64_t = struct let of_int = U64 . of_int let to_int = U64 . to_int let zero = of_int 0 let to_string = U64 . to_string let pp ppf x = Format . fprintf ppf " % s " ( U64 . to_string x ) type t = U64 . t let ctype = Ctypes . uint64_t let ctype_opt = integer_opt ' zero ctype end
module type aliased = sig type t val zero : t val ctype : t Ctypes . typ val ctype_opt : t option Ctypes . typ val of_int : int -> t val to_int : t -> int val to_string : t -> string end
module type alias = sig type x type t = private x val make : x -> t val ctype : t Ctypes . typ val ctype_opt : t option Ctypes . typ val of_int : int -> t val zero : t val to_int : t -> int val pp : Format . formatter -> t -> unit end
module Alias ( X : aliased ) : alias with type x := X . t = struct type t = X . t let make x = x let zero = X . zero let ctype = X . ctype let ctype_opt = X . ctype_opt let of_int = X . of_int let to_int = X . to_int let pp ppf x = Format . fprintf ppf " % s " ( X . to_string x ) end
module Float = struct type t = float let pp = Format . pp_print_float let ctype = Ctypes . float end
module Double = struct type t = float let pp = Format . pp_print_float let ctype = Ctypes . double end
module Void = struct type t = void let ctype = Ctypes . void let pp = Vk__helpers . Pp . abstract end