text
stringlengths
0
601k
let removeEventListener typ listener options = window ## removeEventListener typ listener options
let requestAnimationFrame_polyfill : unit -> unit = fun ( ) -> [ % bs . raw { | // requestAnimationFrame polyfill ( function ( ) { var lastTime = 0 ; var vendors = [ ' ms ' , ' moz ' , ' webkit ' , ' o ' ] ; for ( var x = 0 ; x < vendors . length && ! window . requestAnimationFrame ; ++ x ) { window . requestAnimationFrame = window [ vendors [ x ] ' + RequestAnimationFrame ' ] ; window . cancelAnimationFrame = window [ vendors [ x ] ' + CancelAnimationFrame ' ] || window [ vendors [ x ] ' + CancelRequestAnimationFrame ' ] ; } if ( ! window . requestAnimationFrame ) window . requestAnimationFrame = function ( callback , element ) { var currTime = new Date ( ) . getTime ( ) ; var timeToCall = Math . max ( 0 , 16 - ( currTime - lastTime ) ) ; var id = window . setTimeout ( function ( ) { callback ( currTime + timeToCall ) ; } , timeToCall ) ; lastTime = currTime + timeToCall ; return id ; } ; if ( ! window . cancelAnimationFrame ) window . cancelAnimationFrame = function ( id ) { clearTimeout ( id ) ; } ; } ( ) ) } ] |
let decode_callback ( err : unit -> string ) ( cb : Value . t ) : Value . t -> unit = match Decode . _function cb with | None -> Main . raise_js ( err ( ) ) | Some cb -> fun v -> cb [ | v ] | |> ignore
let send_message ( err : unit -> string ) ( msg : Value . t ) ( dec : ' msg Decode . t ) ( cb : ' msg -> unit ) : unit = match dec msg with | None -> let open Main in log_string ( err ( ) ) ; log_value msg | Some msg -> cb msg
let do_async ( f : unit -> unit ) : unit = Timer . set f 0 |> ignore object method postMessage : ' msg -> unit Js . meth method terminate : unit Js . meth end
type t = worker Js . t
let start ( url : string ) ( dec : ' msg Decode . t ) ( cb : ' msg -> unit ) : t = let open Main in let w = new_global " Worker " [ | Value . string url ] | and cb event = send_message ( fun _ -> " cannot decode message from " ^ url ^ " " " ) \ ( Event . value event ) dec cb in Event_target . add " message " cb ( Obj . magic w ) ; Obj . magic w
let post_message ( msg : Value . t ) ( w : t ) : unit = w ## postMessage msg
let terminate ( w : t ) : unit = w ## terminate
type ' msg worker_function = ( Value . t -> unit ) -> ' msg -> unit
let make ( decode : ' msg Decode . t ) ( f : ' msg worker_function ) : unit = let open Main in let post = match get_global " postMessage " with | None -> raise_js " webworker : < postMessage > function not available " | Some post -> post in let post = decode_callback ( fun _ -> " webworker : < postMessage > is not a function " ) post in let f = f post in make_global " onmessage " ( Value . function1 ( fun msg -> send_message ( fun _ -> " webworker : cannot decode message " ) msg decode f ; Value . undefined ) )
module Simulate = struct type t = ( Value . t -> unit ) option ref let start ( dec : ' rcv Decode . t ) ( cb : ' rcv -> unit ) ( worker_decode : ' msg Decode . t ) ( worker : ' msg worker_function ) : t = let post_to_creator v = send_message ( fun _ -> " main : cannot decode message from worker " ) v dec cb in let post_to_creator v = do_async ( fun _ -> post_to_creator v ) in let f = worker post_to_creator in let post_to_worker v = do_async ( fun _ -> send_message ( fun _ -> " webworker : cannot decode message " ) v worker_decode f ) in ref ( Some post_to_worker ) let post_message ( msg : Value . t ) ( w : t ) : unit = match ! w with | None -> Main . log_string " worker has already been terminated " | Some post -> post msg let terminate ( w : t ) : unit = w := None end
let simulate_js ( name : string ) ( decode : ' msg Decode . t ) ( wfun : ' msg worker_function ) : unit = let open Main in ( fun post -> let post_to_creator = decode_callback ( fun _ -> " webworker : < postMessage > is not a funtion " ) post in let w = Simulate . start ( fun v -> Decode . return v v ) post_to_creator decode wfun in let post_to_worker msg = Simulate . post_message msg w ; Value . undefined and terminate _ = Simulate . terminate w ; Value . undefined in Value . _object [ | " postMessage " , Value . function1 post_to_worker ; " terminate " , Value . function1 terminate ] | ) |> Value . function1 |> make_global name
let kasa_worker = Worker . create " KaSaWorker . js " in let kasa_mailbox = Kasa_client . new_mailbox ( ) in let kamoha_worker = Worker . create " KaMoHaWorker . js " in let kamoha_mailbox = Kamoha_client . new_mailbox ( ) in let kastor_worker = Worker . create " KaStorWorker . js " in let stor_state , update_stor_state = Kastor_client . init_state ( ) in object ( self ) val sim_worker = Worker . create " KaSimWorker . js " val mutable is_running = true initializer let ( ) = kasa_worker . ## onmessage := ( Dom . handler ( fun response_message -> let response_text = response_message . ## data in let ( ) = Common . debug response_text in let ( ) = Kasa_client . receive kasa_mailbox response_text in Js . _true ) ) in let ( ) = kamoha_worker . ## onmessage := ( Dom . handler ( fun response_message -> let response_text = response_message . ## data in let ( ) = Common . debug response_text in let ( ) = Kamoha_client . receive kamoha_mailbox response_text in Js . _true ) ) in let ( ) = kastor_worker . ## onmessage := ( Dom . handler ( fun response_message -> let response_text = response_message . ## data in let ( ) = Common . debug response_text in let ( ) = Kastor_client . receive update_stor_state response_text in Js . _true ) ) in let ( ) = sim_worker . ## onmessage := ( Dom . handler ( fun ( response_message : string Worker . messageEvent Js . t ) -> let response_text : string = response_message . ## data in let ( ) = self # receive response_text in Js . _true ) ) in let ( ) = sim_worker . ## onerror := ( Dom . handler ( fun _ -> let ( ) = is_running <- false in Js . _true ) ) in let ( ) = kasa_worker . ## onerror := ( Dom . handler ( fun _ -> let ( ) = is_running <- false in Js . _true ) ) in let ( ) = kamoha_worker . ## onerror := ( Dom . handler ( fun _ -> let ( ) = is_running <- false in Js . _true ) ) in let ( ) = kastor_worker . ## onerror := ( Dom . handler ( fun _ -> let ( ) = is_running <- false in Js . _true ) ) in ( ) method private sleep timeout = Js_of_ocaml_lwt . Lwt_js . sleep timeout method private post_message ( message_text : string ) : unit = sim_worker ## postMessage ( message_text ) inherit Mpi_api . manager ( ) inherit Kasa_client . new_uniform_client ~ is_running ( : fun ( ) -> true ) ~ post ( : fun message_text -> let ( ) = Common . debug ( Js . string message_text ) in kasa_worker ## postMessage ( message_text ) ) kasa_mailbox inherit Kamoha_client . new_client ~ post ( : fun message_text -> let ( ) = Common . debug ( Js . string message_text ) in kamoha_worker ## postMessage ( message_text ) ) kamoha_mailbox inherit Kastor_client . new_client ~ post ( : fun message_text -> let ( ) = Common . debug ( Js . string message_text ) in kastor_worker ## postMessage ( message_text ) ) stor_state val mutable kasa_locator = [ ] method project_parse ~ patternSharing overwrites = self # secret_project_parse >>= Api_common . result_bind_lwt ~ ok ( : fun out -> let load = self # secret_simulation_load patternSharing out overwrites in let init = self # init_static_analyser out in let locators = init >>= Result_util . fold ~ error ( : fun e -> let ( ) = kasa_locator <- [ ] in Lwt . return ( Result_util . error e ) ) ~ ok ( : fun ( ) -> self # secret_get_pos_of_rules_and_vars >>= Result_util . fold ~ ok ( : fun infos -> let ( ) = kasa_locator <- infos in Lwt . return ( Result_util . ok ( ) ) ) ~ error ( : fun e -> let ( ) = kasa_locator <- [ ] in Lwt . return ( Result_util . error e ) ) ) in load >>= Api_common . result_bind_lwt ~ ok ( : fun ( ) -> locators ) ) method get_influence_map_node_at ~ filename pos : _ Api . result Lwt . t = List . find_opt ( fun ( _ , x ) -> Locality . is_included_in filename pos x ) kasa_locator |> Option_util . map fst |> Result_util . ok ? status : None |> Lwt . return method is_running = is_running method terminate = let ( ) = sim_worker ## terminate in kasa_worker ## terminate method is_computing = self # sim_is_computing || Kasa_client . is_computing kasa_mailbox || self # story_is_computing end
type event_loadend = Web_json . t method abort : unit -> unit method getAllResponseHeaders : unit -> string Js . null method getResponseHeader : string -> string Js . null method _open : string -> string -> bool -> string -> string -> unit method overrideMimeType : string -> unit method send : unit -> unit method send__string : string Js . null -> unit method send__formdata : Web_formdata . t -> unit method send__document : Web_document . t -> unit method setRequestHeader : string -> string -> unit method onreadystatechange : ( event_readystatechange -> unit ) [ @@ bs . get ] [ @@ bs . set ] method readyState : int [ @@ bs . get ] method responseType : string [ @@ bs . get ] [ @@ bs . set ] method response : unresolved Js . null [ @@ bs . get ] method responseText : string [ @@ bs . get ] method responseURL : string [ @@ bs . get ] method responseXML : Web_document . t Js . null [ @@ bs . get ] method status : int [ @@ bs . get ] method statusText : string [ @@ bs . get ] method timeout : float [ @@ bs . get ] [ @@ bs . set ] method upload : xmlHttpRequestUpload [ @@ bs . get ] method withCredentials : bool [ @@ bs . get ] [ @@ bs . set ] method onabort : ( event_abort -> unit ) [ @@ bs . get ] [ @@ bs . set ] method onerror : ( event_error -> unit ) [ @@ bs . get ] [ @@ bs . set ] method onload : ( event_load -> unit ) [ @@ bs . get ] [ @@ bs . set ] method onloadstart : ( event_loadstart -> unit ) [ @@ bs . get ] [ @@ bs . set ] method onprogress : ( event_loadstart -> unit ) [ @@ bs . get ] [ @@ bs . set ] method ontimeout : ( event_timeout -> unit ) [ @@ bs . get ] [ @@ bs . set ] method onloadend : ( event_loadend -> unit ) [ @@ bs . get ] [ @@ bs . set ]
type t = _xmlhttprequest Js . t
type errors = | IncompleteResponse | NetworkError
type body = | EmptyBody | EmptyStringBody | StringBody of string | FormDataBody of Web_formdata . t | FormListBody of ( string * string ) list | DocumentBody of Web_document . t
let abort x = x ## abort ( )
let getAllResponseHeaders x = let open ! Tea_result in match Js . Null . toOption ( x ## getAllResponseHeaders ( ) ) with | None -> Error IncompleteResponse | Some " " -> Error NetworkError | Some s -> Ok s
let getAllResponseHeadersAsList x = let open ! Tea_result in match getAllResponseHeaders x with | Error _ as err -> err | Ok s -> Ok ( s |> Js . String . split " \ r \ n " |> Array . map ( Js . String . splitAtMost " : " ~ limit : 2 ) |> Array . to_list |> List . filter ( fun a -> Array . length a == 2 ) |> List . map ( function | [ | key ; value ] | -> ( key , value ) | _ -> failwith " Cannot happen , already checked length " ) )
let getAllResponseHeadersAsDict x = let module StringMap = Map . Make ( String ) in match getAllResponseHeadersAsList x with | Tea_result . Error _ as err -> err | Tea_result . Ok l -> let insert d ( k , v ) = StringMap . add k v d in Tea_result . Ok ( List . fold_left insert StringMap . empty l )
let getResponseHeader key x = Js . Null . toOption ( x ## getResponse key )
let open_ method ' url ( ? async = true ) ( ? user " " ) = ( ? password " " ) = x = x ## _open method ' url async user password
let overrideMimeType mimetype x = x ## overrideMimeType mimetype
let send body x = match body with | EmptyBody -> x ## send ( ) | EmptyStringBody -> x ## send__string Js . Null . empty | StringBody s -> x ## send__string ( Js . Null . return s ) | FormDataBody f -> x ## send__formdata f | FormListBody l -> let form = List . fold_left ( fun f ( key , value ) -> let ( ) = Web_formdata . append key value f in f ) ( Web_formdata . create ( ) ) l in x ## send__formdata form | DocumentBody d -> x ## send__document d
let setRequestHeader header value x = x ## setRequestHeader header value
type state = | Unsent | Opened | HeadersReceived | Loading | Done
type responseType = | StringResponseType | ArrayBufferResponseType | BlobResponseType | DocumentResponseType | JsonResponseType | TextResponseType | RawResponseType of string
type responseBody = | NoResponse | StringResponse of string | ArrayBufferResponse of unit | BlobResponse of unit | DocumentResponse of Web_document . t | JsonResponse of Web_json . t | TextResponse of string | RawResponse of string * unit
let set_onreadystatechange cb x = x ## onreadystatechange #= cb
let get_onreadystatechange x = x ## onreadystatechange
let readyState x = match x ## readystate with | 0 -> Unsent | 1 -> Opened | 2 -> HeadersReceived | 3 -> Loading | 4 -> Done | i -> failwith ( " Invalid return from ' readystate ' of : " ^ string_of_int i )
let set_responseType typ x = match typ with | StringResponseType -> x ## responseType #= " " | ArrayBufferResponseType -> x ## responseType #= " arraybuffer " | BlobResponseType -> x ## responseType #= " blob " | DocumentResponseType -> x ## responseType #= " document " | JsonResponseType -> x ## responseType #= " json " | TextResponseType -> x ## responseType #= " text " | RawResponseType s -> x ## responseType #= s
let get_responseType x = match x ## responseType with | " " -> StringResponseType | " arraybuffer " -> ArrayBufferResponseType | " blob " -> BlobResponseType | " document " -> DocumentResponseType | " json " -> JsonResponseType | " text " -> TextResponseType | s -> RawResponseType s
let get_response x = match Js . Null . toOption x ## response with | None -> NoResponse | Some resp -> match get_responseType x with | StringResponseType -> StringResponse ( Obj . magic resp ) | ArrayBufferResponseType -> ArrayBufferResponse ( Obj . magic resp ) | BlobResponseType -> BlobResponse ( Obj . magic resp ) | DocumentResponseType -> DocumentResponse ( Obj . magic resp ) | JsonResponseType -> JsonResponse ( Obj . magic resp ) | TextResponseType -> TextResponse ( Obj . magic resp ) | RawResponseType s -> RawResponse ( s , Obj . magic resp )
let get_responseText x = x ## responseText
let get_responseURL x = x ## responseURL
let get_responseXML x = Js . Null . toOption x ## responseXML
let get_status x = x ## status
let get_statusText x = x ## statusText
let set_timeout t x = x ## timeout #= t
let get_timeout x = x ## timeout
let set_withCredentials b x = x ## withCredentials #= b
let get_withCredentials x = x ## withCredentials
let set_onabort cb x = x ## onabort #= cb
let get_onabort x = x ## onabort
let set_onerror cb x = x ## onerror #= cb
let get_onerror x = x ## onerror
let set_onload cb x = x ## onload #= cb
let get_onload x = x ## onload
let set_onloadstart cb x = x ## onloadstart #= cb
let get_onloadstart x = x ## onloadstart
let set_onprogress cb x = x ## onprogress #= cb
let get_onprogress x = x ## onprogress
let set_ontimeout cb x = x ## ontimeout #= cb
let get_ontimeout x = x ## ontimeout
let set_onloadend cb x = x ## onloadend #= cb
let get_onloadend x = x ## onloadend
let rec check_break_expr in_loop ( expr , _ ) = match expr with | VarExpr _ -> true | NilExpr -> true | IntExpr _ -> true | StringExpr _ -> true | CallExpr { call_args ; _ } -> List . for_all ( check_break_expr in_loop ) call_args | OpExpr { op_left ; op_right ; _ } -> check_break_expr in_loop op_left && check_break_expr in_loop op_right | RecordExpr { record_fields ; _ } -> List . for_all ( fun ( _ , init_expr , _ ) -> check_break_expr in_loop init_expr ) record_fields | SeqExpr exprs -> List . for_all ( check_break_expr in_loop ) exprs | AssignExpr { assign_rhs ; _ } -> check_break_expr in_loop assign_rhs | IfExpr { if_test ; if_then ; if_else } -> let if_else_ok = match if_else with | None -> true | Some if_else_expr -> check_break_expr in_loop if_else_expr in check_break_expr in_loop if_test && check_break_expr in_loop if_then && if_else_ok | WhileExpr { while_test ; while_body } -> check_break_expr in_loop while_test && check_break_expr true while_body | ForExpr { for_lo ; for_hi ; for_body ; _ } -> check_break_expr in_loop for_lo && check_break_expr in_loop for_hi && check_break_expr true for_body | BreakExpr -> in_loop | ArrayExpr { array_size ; array_init ; _ } -> check_break_expr in_loop array_size && check_break_expr in_loop array_init | LetExpr { let_decls ; let_body } -> List . for_all ( check_break_decl in_loop ) let_decls && check_break_expr in_loop let_body | VarDecl { var_expr ; _ } -> check_break_expr in_loop var_expr | FunDecl fun_decls -> List . for_all ( fun { fun_body ; _ } -> check_break_expr in_loop fun_body ) fun_decls | TypeDecl _ -> true
let assert_break expr = if not ( check_break_expr false expr ) then failwith " break outside of a loop "
let compare_date ( i1 : Rss2 . item ) ( i2 : Rss2 . item ) = let open Rss2 in match i1 . pubDate , i2 . pubDate with | Some d1 , Some d2 -> Syndic . Date . compare d2 d1 | None , Some _ -> 1 | Some _ , None -> - 1 | None , None -> 0
let post = lazy ( let xml = ` String ( 0 , Http . get ( cwn_base_url ^ " cwn . rss " ) ) in let feed = Syndic . Rss2 . parse ( Xmlm . make_input xml ) in let posts = List . sort compare_date feed . Rss2 . items in match posts with p :: _ -> p | [ ] -> failwith " weekly_news : empty feed " ! )
let cwn_date = lazy ( match ( Lazy . force post ) . Rss2 . pubDate with | Some d -> d | None -> failwith " cwn_date " )
let cwn_html_date ( ) = let d = Lazy . force cwn_date in [ Nethtml . Data ( sprintf " % s % d , % d " ( Utils . en_string_of_month ( Date . month d ) ) ( Date . day d ) ( Date . year d ) ) ]
let rec get_elements tag = function | [ ] -> [ ] | Nethtml . Data _ :: tl -> get_elements tag tl | Nethtml . Element ( t , _ , c ) :: tl -> let e = if t = tag then c else get_elements tag c in e @ get_elements tag tl
let rec drop_until n tag = function | [ ] -> [ ] | Nethtml . Data _ :: tl -> drop_until n tag tl | ( Nethtml . Element ( t , _ , _ ) :: tl ) as l -> if t = tag then if n <= 1 then l else drop_until ( n - 1 ) tag tl else drop_until n tag tl
let rec rm_tags tag = function | [ ] -> [ ] | ( Nethtml . Data _ as e ) :: tl -> e :: rm_tags tag tl | Nethtml . Element ( t , args , sub ) :: tl -> if t = tag then rm_tags tag tl else Nethtml . Element ( t , args , rm_tags tag sub ) :: rm_tags tag tl
let cwn_html_page ( ) = let d = Lazy . force cwn_date in let url = cwn_base_url ^ sprintf " % d . % 02d . % 02d . html " ( Date . year d ) ( Utils . int_of_month ( Date . month d ) ) ( Date . day d ) in let content = Http . get url in let html = Nethtml . parse ( new Netchannels . input_string content ) ~ dtd : Utils . relaxed_html40_dtd in let html = get_elements " body " html in let html = drop_until 2 " p " html in rm_tags " script " html
let cwn_html_summary ( ) = match ( Lazy . force post ) . Rss2 . story with | Rss2 . All ( _ , _ , content ) -> let open Nethtml in Nethtml . parse ( new Netchannels . input_string content ) ~ dtd : Utils . relaxed_html40_dtd | Rss2 . Title _ | Rss2 . Description _ -> failwith " cwn_page "
let ( ) = let contents = ref false in let date = ref false in let specs = [ ( " -- contents " , Arg . Set contents , " output the contents of the latest CWN " ) ; ( " -- date " , Arg . Set date , " output the date of the lastest CWN " ) ; ] in let usage = " weekly_news < option " > in Arg . parse ( Arg . align specs ) ( fun _ -> raise ( Arg . Bad " no anomynous argument " ) ) usage ; if ! contents then let out = new Netchannels . output_channel stdout in Nethtml . write out ( cwn_html_page ( ) ) ; out # close_out ( ) else if ! date then let out = new Netchannels . output_channel stdout in Nethtml . write out ( cwn_html_date ( ) ) ; out # close_out ( ) else ( Arg . usage specs usage ; exit 1 )
module Where = Dune_rpc_private . Where . Make ( struct type ' a t = ' a let return a = a module O = struct let ( let + ) x f = f x let ( let * ) x f = f x end end ) ( struct let read_file f = Ok ( Io . String_path . read_file f ) let analyze_path s = match ( Unix . stat s ) . st_kind with | Unix . S_SOCK -> Ok ` Unix_socket | S_REG -> Ok ` Normal_file | _ | ( exception Unix . Unix_error ( Unix . ENOENT , _ , _ ) ) -> Ok ` Other | exception ( Unix . Unix_error _ as e ) -> Error e end )
let build_dir = lazy ( let build_dir = Path . Build . to_string Path . Build . root in match String . drop_prefix build_dir ~ prefix ( : Sys . getcwd ( ) ^ " " ) / with | None -> build_dir | Some s -> Filename . concat " . " s )
let get ( ) = let env = Env . get Env . initial in match Where . get ~ env ~ build_dir ( : Lazy . force build_dir ) with | Ok s -> s | Error exn -> User_error . raise [ Pp . text " Unable to find dune rpc address " ; Exn . pp exn ]
let default ( ) = Where . default ~ build_dir ( : Lazy . force build_dir ) ( )
let to_socket = function | ` Unix p -> Unix . ADDR_UNIX p | ` Ip ( ` Host host , ` Port port ) -> Unix . ADDR_INET ( Unix . inet_addr_of_string host , port )
module Response = struct module Device_info = struct module Session_info = struct module Connection_info = struct type t = { ip : string option ; last_seen : int option ; user_agent : string option ; } [ @@ deriving accessor ] let encoding = let to_tuple t = t . ip , t . last_seen , t . user_agent in let of_tuple v = let ip , last_seen , user_agent = v in { ip ; last_seen ; user_agent } in let with_tuple = obj3 ( opt " ip " string ) ( opt " last_seen " int ) ( opt " user_agent " string ) in conv to_tuple of_tuple with_tuple end type t = { connections : Connection_info . t list option } [ @@ deriving accessor ] let encoding = let to_tuple t = t . connections in let of_tuple v = let connections = v in { connections } in let with_tuple = obj1 ( opt " connections " ( list Connection_info . encoding ) ) in conv to_tuple of_tuple with_tuple end type t = { sessions : Session_info . t list option } [ @@ deriving accessor ] let encoding = let to_tuple t = t . sessions in let of_tuple v = let sessions = v in { sessions } in let with_tuple = obj1 ( opt " sessions " ( list Session_info . encoding ) ) in conv to_tuple of_tuple with_tuple end type t = { user_id : string option ; devices : ( string * Device_info . t ) list option ; } [ @@ deriving accessor ] let encoding = let to_tuple t = t . user_id , t . devices in let of_tuple v = let user_id , devices = v in { user_id ; devices } in let with_tuple = obj2 ( opt " user_id " string ) ( opt " devices " ( assoc Device_info . encoding ) ) in conv to_tuple of_tuple with_tuple end
let shared_constants_class_name = " pack . ocamljavaConstants " |> UTF8 . of_string |> Name . make_for_class_from_external |> ref
module ClassNameMap = Map . Make ( struct type t = Name . for_class let compare x y = Name . compare_for_class x y end ) end
let constants_name_to_main_name : Name . for_class ClassNameMap . t ref = ref ClassNameMap . empty
let constant_fields : ( Field . t list ) list ClassNameMap . t ref = ref ClassNameMap . empty
let is_constants_class cn = ClassNameMap . mem cn ! constants_name_to_main_name
let main_class_of_constants_class cn = ClassNameMap . find cn ! constants_name_to_main_name
let additional_fields cn = try ClassNameMap . find cn ! constant_fields with Not_found -> [ ] inherit ClassTraversal . default_class_definition_iterator method ! class_definition ( _ : AccessFlag . for_class list ) list ( cn : Name . for_class ) for_class ( _ : Name . for_class option ) option ( _ : Name . for_class list ) list ( fields : Field . t list ) list ( _ : Method . t list ) list ( _ : Attribute . for_class list ) list = let s = Name . internal_utf8_for_class cn in let len = UTF8 . length s in let last_dollar = UTF8 . rindex_from s ( pred len ) len ( UChar . of_char ' $ ' ) ' in let s = UTF8 . substring s 0 ( pred last_dollar ) last_dollar in let cn ' = Name . make_for_class_from_internal s in constants_name_to_main_name := ClassNameMap . add cn cn ' ! constants_name_to_main_name ; constant_fields := ClassNameMap . add cn ' fields ! constant_fields end
module IntSet = Set . Make ( struct type t = int let compare ( x : int ) int ( y : int ) int = Pervasives . compare x y end ) end
let extract_ints l = List . fold_left ( fun acc elem -> match elem with | Annotation . Int_value x -> IntSet . add ( Int32 . to_int x ) x acc | _ -> assert false ) false IntSet . empty l
let linked_classes : UTF8 . t list option ref = ref None
type indices = { read_indices : IntSet . t ; written_indices : IntSet . t ; }
let indices : ( UTF8 . t * indices ) indices list ClassNameMap . t ref = ref ClassNameMap . empty
let merge_maps ( dst : indices ClassNameMap . t ) t ( name , uses ) uses = let class_name = Name . make_for_class_from_external name in let value = try let old = ClassNameMap . find class_name dst in { read_indices = IntSet . union old . read_indices uses . read_indices ; written_indices = IntSet . union old . written_indices uses . written_indices ; } with Not_found -> uses in ClassNameMap . add class_name value dst
let get_used_indices ( ) = ClassNameMap . fold ( fun user used acc -> let merge = match ! linked_classes with | Some l -> List . exists ( fun x -> UTF8 . equal x ( Name . external_utf8_for_class user ) user ) user l | None -> false in if merge then begin List . fold_left merge_maps acc used end else acc ) acc ! indices ClassNameMap . empty
let make_remove_indices_function ( ) = let used_indices = get_used_indices ( ) in if ! Args . verbose then begin used_indices |> ClassNameMap . iter ( fun cn { read_indices ; written_indices } -> cn |> Name . external_utf8_for_class |> UTF8 . to_string |> Printf . printf " indices for % S :\ n " ; IntSet . iter ( Printf . printf " - read % d \ n ) " read_indices ; IntSet . iter ( Printf . printf " - written % d \ n ) " written_indices ) written_indices ; Printf . printf " " %! end ; fun name index -> try let indices = ClassNameMap . find name used_indices in ( not ( IntSet . mem index indices . read_indices ) read_indices ) read_indices && ( not ( IntSet . mem ( ~- 1 ) 1 indices . read_indices ) read_indices ) read_indices with Not_found -> false inherit ArchiveTraversal . default_archive_iterator zip val for_constants = new for_constants method ! class_definition cd = let annotations = Attribute . extract_annotations ( cd . ClassDefinition . attributes :> Attribute . t list ) list in let global_uses = ref [ ] in List . iter ( fun ( n , l ) l -> if Name . equal_for_class n Names . global_uses then begin let class_name = ref ( UTF8 . of_string " dummy . Class ) " in let read_indices = ref IntSet . empty in let written_indices = ref IntSet . empty in List . iter ( fun ( n , v ) v -> let n = UTF8 . to_string n in match n , v with | " className " , Annotation . String_value x -> class_name := x | " readIndices " , Annotation . Array_value x -> read_indices := extract_ints x | " writtenIndices " , Annotation . Array_value x -> written_indices := extract_ints x | _ -> ( ) ) l ; global_uses := ( ! class_name , { read_indices = ! read_indices ; written_indices = ! written_indices ; } ) :: ! global_uses ; end ) end annotations ; indices := ClassNameMap . add cd . ClassDefinition . name ! global_uses ! indices ; let is_constants = List . exists ( fun ( n , _ ) _ -> Name . equal_for_class n Names . constants_class ) constants_class annotations in let is_entry_point = List . exists ( fun ( n , ev ) ev -> if Name . equal_for_class n Names . entry_point then begin List . iter ( fun ( k , v ) v -> if UTF8 . equal k Names . linked_classes then match v with | Annotation . Array_value l -> let l = List . map ( function | Annotation . String_value x -> x | _ -> assert false ) false l in if ! Args . verbose then begin Printf . printf " linked classes :\ n " ; List . iter ( fun cn -> Printf . printf " - % S \ n " ( UTF8 . to_string cn ) cn ) cn l ; Printf . printf " " %! end ; linked_classes := Some l | _ -> assert false ) false ev ; true end else false ) false annotations in if is_constants then ClassDefinition . iter for_constants cd ; if is_entry_point then begin let package_name , _ = Name . split_class_name cd . ClassDefinition . name in let class_name = " ocamljavaConstants " |> UTF8 . of_string |> Name . make_for_class_from_external in shared_constants_class_name := Name . gather_class_name package_name class_name end end
let iter_archive filename = let make_iterator x = new iterator x in ArchiveTraversal . iter_file make_iterator filename
let shared_constants : UTF8 . Set . t ref = ref UTF8 . Set . empty
let add_shared_constant name = shared_constants := UTF8 . Set . add ( Name . utf8_for_field name ) name ! shared_constants
let empty_cstr = let code = Attribute ( { . max_stack = u2 1 ; max_locals = u2 1 ; code = [ Instruction . ALOAD_0 ; Instruction . INVOKESPECIAL ( Names . object_ , Misc . make_method_name " < init " , > ( [ ] , ` Void ) Void ) Void ; Instruction . RETURN ] ; exception_table = [ ] ; attributes = [ ] ; } ) in Method ( . Constructor { cstr_flags = [ ` Private ] ; cstr_descriptor = [ ] ; cstr_attributes = [ ` Code code ] code ; } )
let push_int32 = function | ( - 1l ) 1l -> Instruction . ICONST_M1 | 0l -> Instruction . ICONST_0 | 1l -> Instruction . ICONST_1 | 2l -> Instruction . ICONST_2 | 3l -> Instruction . ICONST_3 | 4l -> Instruction . ICONST_4 | 5l -> Instruction . ICONST_5 | n when n >= ( - 128l ) 128l && n <= 127l -> Instruction . BIPUSH ( s1 ( Int32 . to_int n ) n ) n | n when n >= ( - 32768l ) 32768l && n <= 32767l -> Instruction . SIPUSH ( s2 ( Int32 . to_int n ) n ) n | n -> Instruction . LDC_W ( ` Int n ) n
let push_int64 = function | 0L -> [ Instruction . LCONST_0 ] | 1L -> [ Instruction . LCONST_1 ] | 2L -> [ Instruction . ICONST_2 ; Instruction . I2L ] | 3L -> [ Instruction . ICONST_3 ; Instruction . I2L ] | 4L -> [ Instruction . ICONST_4 ; Instruction . I2L ] | 5L -> [ Instruction . ICONST_5 ; Instruction . I2L ] | n -> [ Instruction . LDC2_W ( ` Long n ) n ]
let push_double x = if x = 0 . 0 then Instruction . DCONST_0 else if x = 1 . 0 then Instruction . DCONST_1 else Instruction . LDC2_W ( ` Double x ) x
let compile_shared_constant_class ( ) = let fields_and_inits = List . map ( fun name -> let underscore = UTF8 . index_from name 0 ( UChar . of_char ' _ ' ) ' _ ' in let typ = UTF8 . substring name 0 ( pred underscore ) underscore in let hexa = UTF8 . substring name ( succ underscore ) underscore ( pred ( UTF8 . length name ) name ) name |> UTF8 . to_string in let field_name = Name . make_for_field name in let field = Field ( { . flags = [ ` Public ; ` Static ; ` Final ] ; name = field_name ; descriptor = ` Class Names . value ; attributes = [ ] ; } ) in let init = match UTF8 . to_string_noerr typ with | " INT " -> ( Scanf . sscanf hexa " % LX " identity |> push_int64 ) push_int64 @ [ Instruction . INVOKESTATIC ( Names . value , Misc . make_method_name " createLong " , ( [ ` Long ] Long , ` Class Names . value ) value ) value ] | " INT32 " -> [ Scanf . sscanf hexa " % lX " identity |> push_int32 ; Instruction . INVOKESTATIC ( Names . value , Misc . make_method_name " createInt32 " , ( [ ` Int ] Int , ` Class Names . value ) value ) value ] | " INT64 " -> ( Scanf . sscanf hexa " % LX " identity |> push_int64 ) push_int64 @ [ Instruction . INVOKESTATIC ( Names . value , Misc . make_method_name " createInt64 " , ( [ ` Long ] Long , ` Class Names . value ) value ) value ] | " NATIVEINT " -> ( Scanf . sscanf hexa " % nX " identity |> Int64 . of_nativeint |> push_int64 ) push_int64 @ [ Instruction . INVOKESTATIC ( Names . value , Misc . make_method_name " createNativeInt " , ( [ ` Long ] Long , ` Class Names . value ) value ) value ] | " FLOAT " -> [ Scanf . sscanf hexa " % LX " identity |> Int64 . float_of_bits |> push_double ; Instruction . INVOKESTATIC ( Names . value , Misc . make_method_name " createDouble " , ( [ ` Double ] Double , ` Class Names . value ) value ) value ] | _ -> assert false in let init = init @ [ Instruction . PUTSTATIC ( ! shared_constants_class_name , field_name , ` Class Names . value ) value ] in field , init ) init ( UTF8 . Set . elements ! shared_constants ) shared_constants in let fields , inits = List . split fields_and_inits in let initializer_meth = let code = Attribute ( { . max_stack = u2 12 ; max_locals = u2 0 ; code = ( List . flatten inits ) inits @ [ Instruction . RETURN ] ; exception_table = [ ] ; attributes = [ ] } ) in Method ( . Initializer { init_flags = [ ` Static ] Static ; init_attributes = [ ` Code code ] code } code ) code in let cd = ClassDefinition ( { . access_flags = [ ` Public ; ` Final ; ` Super ] ; name = ! shared_constants_class_name ; extends = Some Names . object_ ; implements = [ ] ; fields = fields ; methods = [ empty_cstr ; initializer_meth ] ; attributes = [ ] } ) in let buff = ByteBuffer . make_of_size 2048 in let os = OutputStream . make_of_buffer buff in ClassFile . write ( ClassDefinition . encode cd ) cd os ; OutputStream . close os ; let contents = ByteBuffer . contents buff in let path = Name . internal_utf8_for_class ! shared_constants_class_name in let path = UTF8 ( . path ++ ( UTF8 . of_string " . class ) ) " in let path = if ! Args . war then UTF8 ( ( . UTF8 . of_string " WEB - INF / classes ) " / ++ path ) path else path in path , contents