text
stringlengths
0
601k
let todo_of_json json = todo_of_json ( Ezjsonm . value json )
let json_of_todo { title ; url ; completed ; order ; _ } : Ezjsonm . t = let open Ezjsonm in dict [ " title " , ( string title ) ; " url " , ( string url ) ; " completed " , ( bool completed ) ; " order " , ( int order ) ]
let json_of_todos ( todos : todo list ) : Ezjsonm . t = ` A ( List . map todos ~ f ( : fun json -> Ezjsonm . value ( json_of_todo json ) ) )
let get_todos = get " / todos " begin fun _ -> let todos = TodoStorage . fold ( fun _ value acc -> value :: acc ) ! stored_todos [ ] ; in ` Json ( json_of_todos todos ) |> respond ' end
let get_todo = get " / todos /: id " begin fun req -> let todo = TodoStorage . find ( int_of_string ( param req " id " ) ) ! stored_todos ; in ` Json ( json_of_todo todo ) |> respond ' end
let patch_todo = App . patch " / todos /: id " begin fun request -> App . json_of_body_exn request >>| fun json -> let todo = TodoStorage . find ( int_of_string ( param request " id " ) ) ! stored_todos in let updated = updated_todo todo ( Ezjsonm . value json ) in stored_todos := TodoStorage . add todo . id updated ! stored_todos ; ` Json ( json_of_todo updated ) |> respond end
let delete_todo = App . delete " / todos /: id " begin fun request -> stored_todos := TodoStorage . remove ( int_of_string ( param request " id " ) ) ! stored_todos ; respond ' ( ` String " OK " ) end
let post_todos = post " / todos " begin fun request -> App . json_of_body_exn request >>| fun json -> let id = ( Random . int 100000 ) in let todo = todo_of_json json id in stored_todos := TodoStorage . add id todo ! stored_todos ; ` Json ( json_of_todo todo ) |> respond end
let delete_todos = delete " / todos " begin fun _ -> stored_todos := TodoStorage . empty ; respond ' ( ` String " OK " ) end
let accept_options = App . options " " ** begin fun _ -> respond ' ( ` String " OK " ) end
let _ = App . empty |> middleware allow_cors |> accept_options |> get_todos |> get_todo |> patch_todo |> delete_todo |> delete_todos |> post_todos |> App . run_command
let ( . ) <> f g x = f ( g x )
type action = | Add | Set of int * TodoList . status | Clear | UpdatePending of string
let string_of_action = function | Add -> " Add " | Set ( i , TodoList . TODO ) -> sprintf " Set ( % d , TODO ) " i | Set ( i , TodoList . DONE ) -> sprintf " Set ( % d , DONE ) " i | Clear -> " Clear " | UpdatePending s -> sprintf " UpdatePending % S " s
let render_item idx { TodoList . label = l ; status } = let id = sprintf " checkbox % d " idx in let open Html in let open TodoList in let checkbox ~ id ~ onchange ~ state = let attrs = [ A . type_ " checkbox " ; A . id id ; E . onchange ( fun ~ value -> onchange ) ] in let attrs = if state then A . checked true :: attrs else attrs in input ~ attrs Html . empty in match status with | DONE -> checkbox ~ id ~ onchange ( : Set ( idx , TODO ) ) ~ state : true ^^ label ~ attrs [ : A . for_control id ] ( span ~ attrs [ : A . class_ " done " ] ( text l ) ) | TODO -> checkbox ~ id ~ onchange ( : Set ( idx , DONE ) ) ~ state : false ^^ label ~ attrs [ : A . for_control id ] ( text l )
let render_items = let open Html in function | [ ] -> em ( text " Items will appear here " ) | items -> ul ~ attrs [ : A . class_ " no - bullet " ] begin of_list ( List . mapi ( fun i -> li . <> render_item i ) items ) end
let render { TodoList . items ; pending_item } = let open Html in let div ~ classes html = div ~ attrs [ : A . class_ ( String . concat " " classes ) ] html in let text_input ~ classes ~ onenter ~ oninput ~ placeholder value = input ~ attrs [ : A . class_ ( String . concat " " classes ) ; A . type_ " text " ; A . value value ; A . placeholder placeholder ; E . oninput oninput ; E . onkeypress ( fun key_code char_code -> if key_code = Keycode . return then Some onenter else None ) ] empty and button ~ classes ~ enabled ~ onclick label = let classes = [ " button " ] @ ( if enabled then [ ] else [ " disabled " ] ) @ classes in button ~ attrs [ : A . class_ ( String . concat " " classes ) ; E . onclick onclick ] ( text label ) in div ~ classes [ " : panel " ; " radius " ] begin div ~ classes [ " : row " ; " collapse " ] begin div ~ classes [ " : small - 8 " ; " columns " ] begin text_input ~ classes [ " : radius " ] ~ onenter : Add ~ oninput ( : fun ~ value -> UpdatePending value ) ~ placeholder " : Enter new item here " pending_item end ^^ div ~ classes [ " : small - 2 " ; " columns " ] begin button ~ classes [ " : postfix " ] ~ enabled ( : pending_item <> " " ) ~ onclick : Add " Add " end ^^ div ~ classes [ " : small - 2 " ; " columns " ] begin button ~ classes [ " : radius " ; " postfix " ; " alert " ] ~ enabled ( : List . exists ( fun item -> item . TodoList . status = TodoList . DONE ) items ) ~ onclick : Clear " Clear " end ^^ render_items items ^^ hr ( ) ^^ div ~ classes [ " : row " ] begin div ~ classes [ " : small - 12 " ; " columns " ] begin let num_items = List . length items in let num_done_items = List . length ( List . filter ( fun i -> i . TodoList . status = TodoList . DONE ) items ) in text ( sprintf " % d item % s with % d completed " num_items ( if num_items = 1 then " " else " s " ) num_done_items ) end end end end
let update = let open TodoList in function | Add -> add_pending_item | Set ( idx , status ) -> set idx status | Clear -> clear | UpdatePending text -> update_pending text
module ActionFilter = struct type t = action let relevant = function | UpdatePending _ -> false | _ -> true end
module Storage = struct let storage = match Js_browser . Window . local_storage Js_browser . window with | None -> failwith " Storage is not supported by this browser " | Some v -> v let key = " ocaml - vdom - todo - state " let find ( ) = Js_browser . Storage . get_item storage key let set v = Js_browser . Storage . set_item storage key v let init default = match find ( ) with | None -> set default ; default | Some v -> v end
module Model = struct type visibility = Completed | Active | All [ @@ deriving json ] type task = { description : string ; backup : string ; completed : bool ; editing : bool ; id : int ; } [ @@ deriving json ] type t = { tasks : task list ; field : string ; uid : int ; visibility : visibility ; } [ @@ deriving json ] let empty = { tasks = [ ] ; field = " " ; uid = 0 ; visibility = All ; } let new_task desc id = { description = desc ; backup = desc ; completed = false ; editing = false ; id = id } let string_of_visibility v = match v with | Completed -> " Completed " | Active -> " Active " | All -> " All " let from_json s = Deriving_Json . from_string [ % json : t ] s let to_json m = Deriving_Json . to_string [ % json : t ] m end
module Action = struct type action = | Update_field of string | Editing_task of ( int * bool ) | Update_task of ( int * string ) | Add | Delete of int | Delete_complete | Check of ( int * bool ) | Check_all of bool | Change_visibility of Model . visibility | Escape of int | Nop end
module Controller = struct let update m a = let open Action in let open Model in let m = match a with | Add -> let uid = m . uid + 1 in let tasks = let v = String . trim m . field in if v = " " then m . tasks else ( new_task v m . uid ) :: m . tasks in { m with uid = uid ; field = " " ; tasks = tasks } | Update_field field -> { m with field } | Editing_task ( id , is_edit ) -> let update_task t = if ( t . id = id ) then let v = String . trim t . description in if is_edit then { t with editing = is_edit ; backup = v } else { t with editing = is_edit ; backup = " ** should never be displayed " ** } else { t with editing = false } in let l = List . map update_task m . tasks in let l = List . filter ( fun e -> e . description <> " " ) l in { m with tasks = l } | Update_task ( id , task ) -> let update_task t = if ( t . id = id ) then { t with description = task } else t in { m with tasks = List . map update_task m . tasks } | Delete id -> { m with tasks = List . filter ( fun e -> e . id <> id ) m . tasks } | Delete_complete -> { m with tasks = List . filter ( fun e -> not e . completed ) m . tasks } | Check ( id , is_compl ) -> let update_task t = if ( t . id = id ) then { t with completed = is_compl } else t in { m with tasks = List . map update_task m . tasks } | Check_all is_compl -> let update_task t = { t with completed = is_compl } in { m with tasks = List . map update_task m . tasks } | Change_visibility visibility -> { m with visibility = visibility } | Escape id -> let unedit_task t = if ( t . id = id ) then { t with editing = false ; description = t . backup } else t in { m with tasks = List . map unedit_task m . tasks } | Nop -> m in Storage . set @@ Model . to_json m ; m end
module View = struct open Model open Action let task_input m = Vdom . ( input ~ a [ : class_ " new - todo " ; str_prop " placeholder " " What needs to be done " ? ; autofocus ; value m . field ; oninput ( fun s -> Update_field s ) ; onkeydown ( fun e -> match e . which with | 13 -> Add | _ -> Nop ) ] [ ] ) let task_entry m = Vdom . ( elt " header " ~ a [ : class_ " header " ] [ elt " h1 " [ text " todos " ] ; task_input m ] ) let todo_item ( todo : Model . task ) = let input_check = Vdom . ( elt " input " ~ a ( : let l = [ str_prop " type " " checkbox " ; class_ " toggle " ; onclick ( fun _ -> Check ( todo . id , ( not todo . completed ) ) ) ] in if todo . completed then str_prop " checked " " checked " :: l else l ) [ ] ) in let key_handler e = let _ = Js_browser . Console . log Js_browser . console ( Ojs . int_to_js e . Vdom . which ) in if e . Vdom . which = 13 then ( Editing_task ( todo . id , false ) ) else if e . Vdom . which = 27 then ( Action . Escape todo . id ) else Action . Nop in let input_edit ( ) = Vdom . ( input ~ a [ : class_ " edit " ; value todo . description ; str_prop " id " ( Printf . sprintf " todo -% u " todo . id ) ; onblur ( Editing_task ( todo . id , false ) ) ; oninput ( fun s -> Update_task ( todo . id , s ) ) ; onkeydown ( fun e -> key_handler e ) ; ] [ ] ) in let css_class = let l = if todo . completed then [ " completed " ] else [ ] in let l = if todo . editing then " editing " :: l else l in String . concat " " l in Vdom . ( elt " li " ~ a [ : class_ css_class ] [ div ~ a [ : class_ " view " ] [ input_check ; elt " label " ~ a [ : ondblclick ( fun _ -> Editing_task ( todo . id , true ) ) ; ] [ text todo . description ] ; elt " button " ~ a [ : class_ " destroy " ; onclick ( fun _ -> Delete todo . id ; ) ] [ ] ] ; input_edit ( ) ; ] ) let task_list m = let css_visibility tasks = match tasks with | [ ] -> " hidden " | _ -> " visible " in let toggle_input_checked tasks = List . for_all ( fun e -> e . Model . completed ) tasks in let list_of_visible_tasks m = let is_visible todo = match m . Model . visibility with | Model . Completed -> todo . Model . completed | Active -> not todo . completed | All -> true in List . filter is_visible m . Model . tasks in Vdom . ( elt " section " ~ a [ : class_ " main " ; style " visibility " ( css_visibility m . Model . tasks ) ] [ elt " input " ~ a ( : ( if toggle_input_checked m . Model . tasks then [ str_prop " checked " " checked " ] else [ ] ) @ [ type_ " checkbox " ; class_ " toggle - all " ; onclick ( fun _ -> Check_all ( not ( toggle_input_checked m . Model . tasks ) ) ) ; ] ) [ ] ; elt " label " ~ a [ : attr " for " " toggle - all " ] [ text " Mark all as complete " ] ; elt " ul " ~ a [ : class_ " todo - list " ] ( List . map ( todo_item ) ( list_of_visible_tasks m ) ) ] ) let visibility_swap m acc ( uri , visibility ) = let css = if visibility = m . Model . visibility then " selected " else " " in Vdom . ( elt " li " [ elt " a " ~ a [ : str_prop " href " uri ; class_ css ; onclick ( fun _ -> Change_visibility visibility ) ] [ text ( Model . string_of_visibility visibility ) ] ] ) :: acc let controls m = let footer_hidden tasks = match tasks with | [ ] -> true | _ -> false in let button = Vdom . ( [ class_ " clear - completed " ; onclick ( fun _ -> Delete_complete ) ] ) in let button_hidden tasks = let tasks_completed , _ = List . partition ( fun e -> e . Model . completed ) tasks in match tasks_completed with | [ ] -> true | _ -> false in let nb_left tasks = let _ , tasks_left = List . partition ( fun e -> e . Model . completed ) tasks in string_of_int ( List . length tasks_left ) in let item_left tasks = let _ , tasks_left = List . partition ( fun e -> e . Model . completed ) tasks in if ( List . length tasks_left = 1 ) then " item left " else " items left " in let vswap m = List . rev ( List . fold_left ( visibility_swap m ) [ ] [ ( " " , #/ Model . All ) ; ( " #/ active " , Model . Active ) ; ( " #/ completed " , Model . Completed ) ] ) in let html = Vdom . ( elt " footer " ~ a ( ( : class_ " footer " ) :: ( if footer_hidden m . Model . tasks then [ str_prop " hidden " " hidden " ] else [ ] ) ) [ elt " span " ~ a [ : class_ " todo - count " ] [ elt " strong " [ text ( nb_left m . Model . tasks ) ] ; text ( item_left m . Model . tasks ) ] ; elt " ul " ~ a [ : class_ " filters " ] ( vswap m ) ; elt " button " ~ a ( ( : if button_hidden m . Model . tasks then [ str_prop " hidden " " hidden " ] else [ ] ) @ button ) [ text " Clear completed " ] ; ] ) in html let info_footer = Vdom . ( elt " footer " ~ a [ : class_ " info " ] [ elt " p " [ text " Double - click to edit a todo " ] ; elt " p " [ text " TodoMVC with ocaml - vdom " ] ; ] ) let view m = Vdom . ( div ~ a [ : class_ " todomvc - wrapper " ] [ elt " section " ~ a [ : class_ " todoapp " ] [ task_entry m ; task_list m ; controls m ] ; info_footer ] ) end
let app = let m = Model . from_json @@ Storage . init @@ Model . to_json Model . empty in let m = match Js_browser . Location . get_hash ( ) with | " " -> m | hash -> match hash with | " " #/ -> { m with Model . visibility = Model . All } | " #/ active " -> { m with Model . visibility = Model . Active } | " #/ completed " -> { m with Model . visibility = Model . Completed } | _ -> m in Vdom . simple_app ~ init : m ~ view : View . view ~ update : Controller . update ( )
let run ( ) = Vdom_blit . run app |> Vdom_blit . dom |> Js_browser . Element . append_child ( Js_browser . Document . body Js_browser . document )
let ( ) = Js_browser . Window . set_onload Js_browser . window run
module type S = sig type todo = { id : int ; content : string ; } type error = | Database_error val migrate : unit -> ( unit , error ) result Lwt . t val rollback : unit -> ( unit , error ) result Lwt . t val get_all : unit -> ( todo list , error ) result Lwt . t val add : string -> ( unit , error ) result Lwt . t val remove : int -> ( unit , error ) result Lwt . t val clear : unit -> ( unit , error ) result Lwt . t end
module Make ( Db : module type of Db ) = struct let pool = Db . create_pool ( ) type todo = { id : int ; content : string ; } type error = | Database_error module Q = struct let create_todos_table = Caqti_request . exec Caqti_type . unit { | CREATE TABLE todos ( id SERIAL NOT NULL PRIMARY KEY , content VARCHAR ) } | let drop_todos_table = Caqti_request . exec Caqti_type . unit " DROP TABLE todos " let get_all_todos = Caqti_request . collect Caqti_type . unit Caqti_type . ( tup2 int string ) " SELECT id , content FROM todos " let add_todo = Caqti_request . exec Caqti_type . string " INSERT INTO todos ( content ) VALUES ( ) " ? let remove_todo = Caqti_request . exec Caqti_type . int " DELETE FROM todos WHERE id = " ? let clear_todos = Caqti_request . exec Caqti_type . unit " DELETE FROM todos " end let migrate_internal ( module Db : Caqti_lwt . CONNECTION ) = Db . exec Q . create_todos_table ( ) let migrate ( ) = let % lwt result = Caqti_lwt . Pool . use migrate_internal pool in match result with | Ok ( ) -> Ok ( ) |> Lwt . return | Error _e -> Error Database_error |> Lwt . return let rollback_internal ( module Db : Caqti_lwt . CONNECTION ) = Db . exec Q . drop_todos_table ( ) let rollback ( ) = let % lwt result = Caqti_lwt . Pool . use rollback_internal pool in match result with | Ok ( ) -> Ok ( ) |> Lwt . return | Error _e -> Error Database_error |> Lwt . return let get_all_internal ( module Db : Caqti_lwt . CONNECTION ) = Db . fold Q . get_all_todos ( fun ( id , content ) acc -> { id = id ; content = content } :: acc ) ( ) [ ] let get_all ( ) = let % lwt todo_result = Caqti_lwt . Pool . use get_all_internal pool in match todo_result with | Ok todo_list -> Ok todo_list |> Lwt . return | Error _e -> Error Database_error |> Lwt . return let add_internal content ( module Db : Caqti_lwt . CONNECTION ) = Db . exec Q . add_todo content let add content = let % lwt result = Caqti_lwt . Pool . use ( add_internal content ) pool in match result with | Ok ( ) -> Ok ( ) |> Lwt . return | Error _e -> Error Database_error |> Lwt . return let remove_internal id ( module Db : Caqti_lwt . CONNECTION ) = Db . exec Q . remove_todo id let remove id = let % lwt result = Caqti_lwt . Pool . use ( remove_internal id ) pool in match result with | Ok ( ) -> Ok ( ) |> Lwt . return | Error _e -> Error Database_error |> Lwt . return let clear_internal ( module Db : Caqti_lwt . CONNECTION ) = Db . exec Q . clear_todos ( ) let clear ( ) = let % lwt result = Caqti_lwt . Pool . use clear_internal pool in match result with | Ok ( ) -> Ok ( ) |> Lwt . return | Error _e -> Error Database_error |> Lwt . return end
type rounding_mode = FE_DOWNWARD | FE_TONEAREST | FE_TOWARDZERO | FE_UPWARD
let hex_of_float f = format_float " % a " f
let test1 ( mant : int64 ) ( exp : int ) = let expected = ldexp ( Int64 . to_float mant ) exp in let actual = Z . to_float ( Z . shift_left ( Z . of_int64 mant ) exp ) in if actual = expected then true else begin printf " % Ld * 2 ^% d : expected % s , got % s \ n " mant exp ( hex_of_float expected ) ( hex_of_float actual ) ; false end
let rnd64 ( ) = let m1 = Random . bits ( ) in let m2 = Random . bits ( ) in let m3 = Random . bits ( ) in Int64 . ( logor ( of_int m1 ) ( logor ( shift_left ( of_int m2 ) 30 ) ( shift_left ( of_int m3 ) 60 ) ) )
let testN numrounds = printf " ( % d tests ) . . . " %! numrounds ; let errors = ref 0 in for i = 1 to numrounds do let m = Random . int64 Int64 . max_int in if not ( test1 m 0 ) then incr errors ; if not ( test1 ( Int64 . neg m ) 0 ) then incr errors done ; for i = 1 to numrounds do let m = rnd64 ( ) in let exp = Random . int 1100 in if not ( test1 m exp ) then incr errors done ; for i = 0 to 15 do let m = Int64 . ( add 0xfffffffffffff0L ( of_int i ) ) in if not ( test1 m 32 ) then incr errors ; if not ( test1 ( Int64 . neg m ) 32 ) then incr errors done ; if ! errors = 0 then printf " passed \ n " %! else printf " FAILED ( % d errors ) \ n " %! ! errors
let testQ1 ( mant1 : int64 ) ( exp1 : int ) ( mant2 : int64 ) ( exp2 : int ) = let expected = ldexp ( Int64 . to_float mant1 ) exp1 . / ldexp ( Int64 . to_float mant2 ) exp2 in let actual = Q . to_float ( Q . make ( Z . shift_left ( Z . of_int64 mant1 ) exp1 ) ( Z . shift_left ( Z . of_int64 mant2 ) exp2 ) ) in if compare actual expected = 0 then true else begin printf " % Ld * 2 ^% d / % Ld * 2 ^% d : expected % s , got % s \ n " mant1 exp1 mant2 exp2 ( hex_of_float expected ) ( hex_of_float actual ) ; false end
let testQN numrounds = printf " ( % d tests ) . . . " %! numrounds ; let errors = ref 0 in if not ( testQ1 0L 0 1L 0 ) then incr errors ; if not ( testQ1 1L 0 0L 0 ) then incr errors ; if not ( testQ1 ( - 1L ) 0 0L 0 ) then incr errors ; if not ( testQ1 0L 0 0L 0 ) then incr errors ; for i = 1 to numrounds do let m1 = Random . int64 0x20000000000000L in let m1 = if Random . bool ( ) then m1 else Int64 . neg m1 in let exp1 = Random . int 500 in let m2 = Random . int64 0x20000000000000L in let exp2 = Random . int 500 in if not ( testQ1 m1 exp1 m2 exp2 ) then incr errors done ; if ! errors = 0 then printf " passed \ n " %! else printf " FAILED ( % d errors ) \ n " %! ! errors
let _ = let numrounds = if Array . length Sys . argv >= 2 then int_of_string Sys . argv . ( 1 ) else 100_000 in printf " Default rounding mode ( Z ) " ; testN numrounds ; printf " Default rounding mode ( Q ) " ; testQN numrounds ; if setround FE_TOWARDZERO then begin printf " Round toward zero ( Z ) " ; testN numrounds ; printf " Round toward zero ( Q ) " ; testQN numrounds end else begin printf " Round toward zero not supported , skipping \ n " end ; if setround FE_DOWNWARD then begin printf " Round downward ( Z ) " ; testN numrounds ; printf " Round downward ( Q ) " ; testQN numrounds end else begin printf " Round downward not supported , skipping \ n " end ; if setround FE_UPWARD then begin printf " Round upward ( Z ) " ; testN numrounds ; printf " Round upward ( Q ) " ; testQN numrounds end else begin printf " Round upward not supported , skipping \ n " end ; if setround FE_TONEAREST then begin printf " Round to nearest ( Z ) " ; testN numrounds ; printf " Round to nearest ( Q ) " ; testQN numrounds end else begin printf " Round to nearest not supported , skipping \ n " end
let may x name f = match x with None -> [ ] | Some a -> [ TkToken name ; TkToken ( f a ) ]
let cbool x = if x then " 1 " else " 0 "
let id x = x
let togl_options_optionals f = fun ? accum ? accumalphasize ? accumbluesize ? accumgreensize ? accumredsize ? alpha ? alphasize ? auxbuffers ? bluesize ? depth ? depthsize ? double ? greensize ? height ? overlay ? privatecmap ? redsize ? rgba ? stencil ? stencilsize ? stereo ? width -> f ( may accum " - accum " cbool
type font = [ ` Fixed_8x13 | ` Fixed_9x15 | ` Times_10 | ` Times_24 | ` Helvetica_10 | ` Helvetica_12 | ` Helvetica_18 | ` Xfont of string ] = " ml_Togl_LoadBitmapFont " = " ml_Togl_UnloadBitmapFont " = " ml_Togl_GetOverlayTransparentValue " = " ml_Togl_DumpToEpsFile "
type widget = w Widget . widget
let togl_table = Hashtbl . create 7
let wrap f ( w : widget ) = let togl = try Hashtbl . find togl_table w with Not_found -> raise ( TkError " Unreferenced togl widget " ) in f togl
let render = wrap _post_redisplay
let swap_buffers = wrap _swap_buffers
let height = wrap _height
let width = wrap _width
let load_bitmap_font = wrap _load_bitmap_font
let unload_bitmap_font = wrap _unload_bitmap_font
let use_layer = wrap _use_layer
let show_overlay = wrap _show_overlay
let hide_overlay = wrap _hide_overlay
let overlay_redisplay = wrap _post_overlay_redisplay
let exists_overlay = wrap _exists_overlay
let get_overlay_transparent_value = wrap _get_overlay_transparent_value
let make_current togl = ignore ( tkEval [ | TkToken ( Widget . name togl ) ; TkToken " makecurrent " ] ) |
let null_func _ = ( )
let display_table = Hashtbl . create 7
let cb_of_togl table togl = try let key = _ident togl in let cb = Hashtbl . find table key in ignore ( tkEval [ | TkToken key ; TkToken " makecurrent " ] ) ; | cb ( ) with Not_found -> ( )
let callback_table = [ | null_func ; cb_of_togl display_table ; cb_of_togl reshape_table ; null_func ; null_func ; cb_of_togl overlay_table ; null_func ] |
let ( ) = Callback . register " togl_callbacks " callback_table ; Callback . register " togl_prerr " ( fun msg -> prerr_string msg ; flush stderr )
let callback_func table ( w : widget ) ~ cb = let key = Widget . name w in ( try Hashtbl . remove table key with Not_found -> ( ) ) ; Hashtbl . add table key cb
let display_func = callback_func display_table
let reshape_func w ~ cb = make_current w ; cb ( ) ; callback_func reshape_table w ~ cb
let overlay_display_func = callback_func overlay_table
let dump_to_eps_file ~ filename ( ? rgba = false ) ? render togl = let render = match render with Some f -> f | None -> in callback_table . ( render_id ) <- ( fun _ -> render ( ) ) ; _dump_to_eps_file togl filename rgba
let dump_to_eps_file ~ filename ? rgba ? render = wrap ( dump_to_eps_file ~ filename ? rgba ? render )
let rec timer_func ~ ms ~ cb = ignore ( Timer . add ~ ms ~ callback ( : fun ( ) -> cb ( ) ; timer_func ~ ms ~ cb ) )
let configure ? height ? width w = let options = may height " - height " cint @ may width " - width " cint in tkEval [ | TkToken ( Widget . name w ) ; TkTokenList options ] |
let ready = ref false
let init_togl ( ) = init ( ) ; _create_func ( ) ; _display_func ( ) ; _reshape_func ( ) ; _overlay_display_func ( ) ; _destroy_func ( ) ; ready := true
let create ? name = togl_options_optionals ( fun options parent -> prerr_endline " Before init " ; if not ! ready then init_togl ( ) ; prerr_endline " After init " ; let w : widget = let togl = ref None in callback_table . ( create_id ) <- callback_table . ( destroy_id ) <- ( fun t -> prerr_endline " Before create " ; let command = let _res : string = in prerr_endline " After create " ; match ! togl with None -> raise ( TkError " Togl widget creation failed " ) | Some t -> w )
module Make ( Loc : Sig . Loc ) module Loc = Loc ; open Sig ; type t = camlp4_token ; type token = t ; value to_string = fun [ KEYWORD s -> sprintf " KEYWORD % S " s | SYMBOL s -> sprintf " SYMBOL % S " s | LIDENT s -> sprintf " LIDENT % S " s | UIDENT s -> sprintf " UIDENT % S " s | INT _ s -> sprintf " INT % s " s | INT32 _ s -> sprintf " INT32 % sd " s | INT64 _ s -> sprintf " INT64 % sd " s | NATIVEINT _ s -> sprintf " NATIVEINT % sd " s | FLOAT _ s -> sprintf " FLOAT % s " s | CHAR _ s -> sprintf " CHAR ' % s ' " s | STRING _ s -> sprintf " STRING " \% s " " \ s | LABEL s -> sprintf " LABEL % S " s | OPTLABEL s -> sprintf " OPTLABEL % S " s | ANTIQUOT n s -> sprintf " ANTIQUOT % s : % S " n s | QUOTATION x -> sprintf " QUOTATION { q_name =% S ; q_loc =% S ; q_shift =% d ; q_contents =% S } " x . q_name x . q_loc x . q_shift x . q_contents | COMMENT s -> sprintf " COMMENT % S " s | BLANKS s -> sprintf " BLANKS % S " s | NEWLINE -> sprintf " NEWLINE " | EOI -> sprintf " EOI " | ESCAPED_IDENT s -> sprintf " ESCAPED_IDENT % S " s | LINE_DIRECTIVE i None -> sprintf " LINE_DIRECTIVE % d " i | LINE_DIRECTIVE i ( Some s ) -> sprintf " LINE_DIRECTIVE % d % S " i s ] ; value print ppf x = pp_print_string ppf ( to_string x ) ; value match_keyword kwd = fun [ KEYWORD kwd ' when kwd = kwd ' -> True | _ -> False ] ; value extract_string = fun [ KEYWORD s | SYMBOL s | LIDENT s | UIDENT s | INT _ s | INT32 _ s | INT64 _ s | NATIVEINT _ s | FLOAT _ s | CHAR _ s | STRING _ s | LABEL s | OPTLABEL s | COMMENT s | BLANKS s | ESCAPED_IDENT s -> s | tok -> invalid_arg ( " Cannot extract a string from this token : " ^ to_string tok ) ] ; module Error = struct type t = [ Illegal_token of string | Keyword_as_label of string | Illegal_token_pattern of string and string | Illegal_constructor of string ] ; exception E of t ; value print ppf = fun [ Illegal_token s -> fprintf ppf " Illegal token ( % s ) " s | Keyword_as_label kwd -> fprintf ppf " ` % s ' is a keyword , it cannot be used as label name " kwd | Illegal_token_pattern p_con p_prm -> fprintf ppf " Illegal token pattern : % s % S " p_con p_prm | Illegal_constructor con -> fprintf ppf " Illegal constructor % S " con ] ; value to_string x = let b = Buffer . create 50 in let ( ) = bprintf b " % a " print x in Buffer . contents b ; end ; let module M = ErrorHandler . Register Error in ( ) ; module Filter = struct type token_filter = stream_filter t Loc . t ; type t = { is_kwd : string -> bool ; filter : mutable token_filter } ; value err error loc = raise ( Loc . Exc_located loc ( Error . E error ) ) ; value keyword_conversion tok is_kwd = match tok with [ SYMBOL s | LIDENT s | UIDENT s when is_kwd s -> KEYWORD s | ESCAPED_IDENT s -> LIDENT s | _ -> tok ] ; value check_keyword_as_label tok loc is_kwd = let s = match tok with [ LABEL s -> s | OPTLABEL s -> s | _ -> " " ] in if s <> " " && is_kwd s then err ( Error . Keyword_as_label s ) loc else ( ) ; value check_unknown_keywords tok loc = match tok with [ SYMBOL s -> err ( Error . Illegal_token s ) loc | _ -> ( ) ] ; value error_no_respect_rules p_con p_prm = raise ( Error . E ( Error . Illegal_token_pattern p_con p_prm ) ) ; value check_keyword _ = True ; value error_on_unknown_keywords = ref False ; value rec ignore_layout = parser [ [ : ` ( COMMENT _ | BLANKS _ | NEWLINE | LINE_DIRECTIVE _ _ , _ ) ; s ] : -> ignore_layout s | [ : ` x ; s ] : -> [ : ` x ; ignore_layout s ] : | [ : ] : -> [ : ] : ] ; value mk is_kwd = { is_kwd = is_kwd ; filter = ignore_layout } ; value filter x = let f tok loc = do { let tok = keyword_conversion tok x . is_kwd ; check_keyword_as_label tok loc x . is_kwd ; if error_on_unknown_keywords . val then check_unknown_keywords tok loc else ( ) ; debug token " [ @< hov 2 > Lexer before filter :@ % a @ at @ % a ] . " @@ print tok Loc . dump loc in ( tok , loc ) } in let rec filter = parser [ [ : ` ( tok , loc ) ; s ] : -> [ : ` f tok loc ; filter s ] : | [ : ] : -> [ : ] : ] in let rec tracer = parser [ [ : ` ( ( _tok , _loc ) as x ) ; xs ] : -> debug token " [ @< hov 2 > Lexer after filter :@ % a @ at @ % a ] . " @@ print _tok Loc . dump _loc in [ : ` x ; tracer xs ] : | [ : ] : -> [ : ] : ] in fun strm -> tracer ( x . filter ( filter strm ) ) ; value define_filter x f = x . filter := f x . filter ; value keyword_added _ _ _ = ( ) ; value keyword_removed _ _ = ( ) ; end ; end ;
module Eval = struct value valch x = Char . code x - Char . code ' 0 ' ; value valch_hex x = let d = Char . code x in if d >= 97 then d - 87 else if d >= 65 then d - 55 else d - 48 ; value rec skip_indent = parser [ [ : ` ' ' | ' \ t ' ; s ] : -> skip_indent s | [ : ] : -> ( ) ] ; value skip_opt_linefeed = parser [ [ : ` ' \ 010 ' ] : -> ( ) | [ : ] : -> ( ) ] ; value chr c = if c < 0 || c > 255 then failwith " invalid char token " else Char . chr c ; value rec backslash = parser [ [ : ` ' \ 010 ' ] : -> ' \ 010 ' | [ : ` ' \ 013 ' ] : -> ' \ 013 ' | [ : ` ' n ' ] : -> ' \ n ' | [ : ` ' r ' ] : -> ' \ r ' | [ : ` ' t ' ] : -> ' \ t ' | [ : ` ' b ' ] : -> ' \ b ' | [ : ` ' ' \\ ] : -> ' ' \\ | [ : ` ' " ' ] : -> ' " ' | [ : ` ' ' ' ] : -> ' ' ' | [ : ` ' ' ] : -> ' ' | [ : ` ( ' 0 ' . . ' 9 ' as c1 ) ; ` ( ' 0 ' . . ' 9 ' as c2 ) ; ` ( ' 0 ' . . ' 9 ' as c3 ) ] : -> chr ( 100 * ( valch c1 ) + 10 * ( valch c2 ) + ( valch c3 ) ) | [ : ` ' x ' ; ` ( ' 0 ' . . ' 9 ' | ' a ' . . ' f ' | ' A ' . . ' F ' as c1 ) ; ` ( ' 0 ' . . ' 9 ' | ' a ' . . ' f ' | ' A ' . . ' F ' as c2 ) ] : -> chr ( 16 * ( valch_hex c1 ) + ( valch_hex c2 ) ) ] ; value rec backslash_in_string strict store = parser [ [ : ` ' \ 010 ' ; s ] : -> skip_indent s | [ : ` ' \ 013 ' ; s ] : -> do { skip_opt_linefeed s ; skip_indent s } | [ : x = backslash ] : -> store x | [ : ` c when not strict ] : -> do { store ' ' ; \\ store c } | [ : ] : -> failwith " invalid string token " ] ; value char s = if String . length s = 1 then s . [ 0 ] else if String . length s = 0 then failwith " invalid char token " else match Stream . of_string s with parser [ [ : ` ' ' ; \\ x = backslash ] : -> x | [ : ] : -> failwith " invalid char token " ] ; value string ? strict s = let buf = Buffer . create 23 in let store = Buffer . add_char buf in let rec parse = parser [ [ : ` ' ' ; \\ _ = backslash_in_string ( strict <> None ) store ; s ] : -> parse s | [ : ` c ; s ] : -> do { store c ; parse s } | [ : ] : -> Buffer . contents buf ] in parse ( Stream . of_string s ) ; end ;
let niter = ref 0
let token = ref 0
let process ( n , ins , outs , nprocs ) = let buf = String . make 1 ' . ' in while buf <> " " - do Unix . read ins . ( n ) buf 0 1 ; if n = 0 then begin decr niter ; if ! niter <= 0 then buf . [ 0 ] <- ' ' ; - end ; let next = if n + 1 >= nprocs then 0 else n + 1 in Unix . write outs . ( next ) buf 0 1 done
let main ( ) = let nprocs = try int_of_string Sys . argv . ( 1 ) with _ -> 100 in let iter = try int_of_string Sys . argv . ( 2 ) with _ -> 1000 in let ins = Array . make nprocs Unix . stdin in let outs = Array . make nprocs Unix . stdout in let threads = Array . make nprocs ( Thread . self ( ) ) in for n = 0 to nprocs - 1 do let ( i , o ) = Unix . pipe ( ) in ins . ( n ) <- i ; outs . ( n ) <- o done ; niter := iter ; for i = 0 to nprocs - 1 do threads . ( i ) <- Thread . create process ( i , ins , outs , nprocs ) done ; Unix . write outs . ( 0 ) " X " 0 1 ; for i = 0 to nprocs - 1 do Thread . join threads . ( i ) done
type domain = [ ` Absolute of string list | ` Sub of string list ]
type name = { domain : domain ; name : string }
let pp_print_domains : domain Formatf . t = fun fmt -> function | ` Absolute ( _a0 : string list ) -> Format . fprintf fmt " . % s " ( String . concat " . " _a0 ) | ` Sub _a0 -> Format . fprintf fmt " % s " ( String . concat " . " _a0 )
let pp_print_name fmt ( x : name ) = Format . fprintf fmt " % a . % a " pp_print_domains x . domain Format . pp_print_string x . name
let string_of_name = Formatf . to_string pp_print_name
type quot = { loc : loc ; txt : string ; name : name ; meta : string option ; shift : int ; retract : int ; }
type txt = { loc : loc ; txt : string ; }
type op = { loc : loc ; txt : string ; level : int ; }
type ant = { loc : loc ; txt : string ; cxt : string option ; kind : string ; shift : int ; retract : int ; }
let ant_expand p ( x : ant ) = let content = String . sub x . txt x . shift ( String . length x . txt - x . retract - x . shift ) in let loc = Location_util . join { x . loc with loc_start = { x . loc . loc_start with pos_cnum = x . loc . loc_start . pos_cnum + x . shift } } in p loc content
let mk_ant ? c ( x : ant ) = match c with | None -> ` Ant ( x . loc , x ) | Some _ -> ` Ant ( x . loc , { x with cxt = c } )
let pp_print_ant fmt ( x : ant ) = Format . fprintf fmt " cxt :% S ; content :% S " ( match x . cxt with None " " ->| Some s -> s ) x . txt
let pp_print_quot : Format . formatter -> quot -> unit = fun fmt { name ; meta ; shift ; txt ; loc ; retract } -> Format . fprintf fmt " [ @< 1 { > name =% a ; ; @ loc =% a ; @ meta =% a ; ; @ shift =% a ; @ retract =% a ; ; @ txt =% a } ] " @ pp_print_name name ( Formatf . pp_print_option Formatf . pp_print_string ) meta Locf . pp_print_t loc Format . pp_print_int shift Format . pp_print_int retract Format . pp_print_string txt
type ' a expand_fun = Locf . t -> string option -> string -> ' a
type quotation = [ ` Quot of quot ]
type dir_quotation = [ ` DirQuotation of quot ]
type line = { loc : loc ; txt : string ; line : int ; name : string option ; }
type space_token = [ ` Comment of txt | ` Blank of txt | ` Newline of txt | ` LINE_DIRECTIVE of line ]
type t = [ ` Key of txt | ` Lid of txt | ` Uid of txt | ` Int of txt | ` Int32 of txt | ` Int64 of txt | ` Nativeint of txt | ` Flo of txt | ` Chr of txt | ` Label of txt | ` Optlabel of txt | ` Str of txt | ` EOI of txt | ` Pre of txt | ` Inf of op | ` Quot of quot | ` DirQuotation of quot | ` Ant of ant ]
type tag = [ ` Key | ` Lid | ` Uid | ` Int | ` Int32 | ` Int64 | ` Nativeint | ` Flo | ` Chr | ` Label | ` Optlabel | ` Str | ` EOI | ` Pre | ` Inf | ` Quot | ` DirQuotation | ` Ant ]