text
stringlengths
0
601k
let subst x t ' = pre_subst ( subst_var x t ' ) ; ; [ %% expect { | } ] ; ; |
type ( _ , _ ) alist = | Anil : ( ' n , ' n ) alist | Asnoc : ( ' m , ' n ) alist * ' m term * ' m succ fin -> ( ' m succ , ' n ) alist
let rec sub : type m n . ( m , n ) alist -> m fin -> n term = function | Anil -> var | Asnoc ( s , t , x ) -> comp_subst ( sub s ) ( subst_var x t ) [ %% expect { |
type ( _ , _ ) alist = Anil : ( ' n , ' n ) alist | Asnoc : ( ' m , ' n ) alist * ' m term * ' m succ fin -> ( ' m succ , ' n ) alist } ] ; ; |
let rec append : type m n l . ( m , n ) alist -> ( l , m ) alist -> ( l , n ) alist = fun r s -> match s with | Anil -> r | Asnoc ( s , t , x ) -> Asnoc ( append r s , t , x ) [ %% expect { | } ] ; ; |
type _ ealist = EAlist : ( ' a , ' b ) alist -> ' a ealist
let asnoc a t ' x = EAlist ( Asnoc ( a , t ' , x ) ) [ %% expect { |
type _ ealist = EAlist : ( ' a , ' b ) alist -> ' a ealist < fun > } ] ; ; |
let rec weaken_fin : type n . n fin -> n succ fin = function | FZ -> FZ | FS x -> FS ( weaken_fin x )
let weaken_term t = pre_subst ( fun x -> Var ( weaken_fin x ) ) t
let rec weaken_alist : type m n . ( m , n ) alist -> ( m succ , n succ ) alist = function | Anil -> Anil | Asnoc ( s , t , x ) -> Asnoc ( weaken_alist s , weaken_term t , weaken_fin x )
let rec sub ' : type m . m ealist -> m fin -> m term = function | EAlist Anil -> var | EAlist ( Asnoc ( s , t , x ) ) -> comp_subst ( sub ' ( EAlist ( weaken_alist s ) ) ) ( fun t ' -> weaken_term ( subst_var x t t ' ) )
let subst ' d = pre_subst ( sub ' d ) ; ; [ %% expect { | } ] ; ; |
let flex_flex x y = match thick x y with | Some y ' -> asnoc Anil ( Var y ' ) x | None -> EAlist Anil
let flex_rigid x t = bind ( check x t ) ( fun t ' -> Some ( asnoc Anil t ' x ) )
let rec amgu : type m . m term -> m term -> m ealist -> m ealist option = fun s t acc -> match s , t , acc with | Leaf , Leaf , _ -> Some acc | Leaf , Fork _ , _ -> None | Fork _ , Leaf , _ -> None | Fork ( s1 , s2 ) , Fork ( t1 , t2 ) , _ -> bind ( amgu s1 t1 acc ) ( amgu s2 t2 ) | Var x , Var y , EAlist Anil -> let IS = fin_succ x in Some ( flex_flex x y ) | Var x , t , EAlist Anil -> let IS = fin_succ x in flex_rigid x t | t , Var x , EAlist Anil -> let IS = fin_succ x in flex_rigid x t | s , t , EAlist ( Asnoc ( d , r , z ) ) -> bind ( amgu ( subst z r s ) ( subst z r t ) ( EAlist d ) ) ( fun ( EAlist d ) -> Some ( asnoc d r z ) )
let mgu s t = amgu s t ( EAlist Anil ) ; ; [ %% expect { | } ] ; ; |
let s = Fork ( Var FZ , Fork ( Var ( FS ( FS FZ ) ) , Leaf ) )
let t = Fork ( Var ( FS FZ ) , Var ( FS FZ ) )
let d = match mgu s t with Some x -> x | None -> failwith " mgu "
let s ' = subst ' d s
let t ' = subst ' d t ; ; [ %% expect { | EAlist ( Asnoc ( Asnoc ( Anil , Fork ( Var FZ , Leaf ) , FZ ) , Var FZ , FZ ) ) Fork ( Fork ( Var FZ , Leaf ) , Fork ( Var FZ , Leaf ) ) Fork ( Fork ( Var FZ , Leaf ) , Fork ( Var FZ , Leaf ) ) } ] ; ; |
let rec equal s t = match s , t with | T . Int , T . Int -> true | T . Bool , T . Bool -> true | T . Arrow ( t1 , t2 ) , T . Arrow ( s1 , s2 ) -> ( equal t1 s1 ) && ( equal t2 s2 ) | T . Product ss , T . Product ts -> List . for_all ( fun ( s , t ) -> equal s t ) ( List . combine ss ts ) | T . TVar { contents = Some s ' } , _ -> equal s ' t | _ , T . TVar { contents = Some t ' } -> equal s t ' | T . TVar x , T . TVar y -> x == y | _ , _ -> false
let a1 : ( T . tp option ) ref = ref ( None ) ; ;
let a2 : ( T . tp option ) ref = ref ( None ) ; ;
let a3 : ( T . tp option ) ref = ref ( None ) ; ;
let a4 : ( T . tp option ) ref = ref ( None ) ; ;
let a5 : ( T . tp option ) ref = ref ( None ) ; ;
let a6 : ( T . tp option ) ref = ref ( None ) ; ;
let a7 : ( T . tp option ) ref = ref ( None ) ; ;
let a8 : ( T . tp option ) ref = ref ( None ) ; ;
let t1 = T . Arrow ( T . Product [ T . TVar ( a1 ) ; T . TVar ( a1 ) ] , T . TVar ( a2 ) ) ; ;
let t2 = T . Arrow ( T . Product [ T . Int ; T . Int ] , T . TVar ( a1 ) ) ; ;
let t3 = T . Arrow ( T . Product [ T . TVar ( a3 ) ; T . TVar ( a4 ) ] , T . TVar ( a4 ) ) ; ;
let t4 = T . Arrow ( T . Product [ T . TVar ( a4 ) ; T . TVar ( a3 ) ] , T . TVar ( a3 ) ) ; ;
let t5 = T . Arrow ( T . Product [ T . TVar ( a5 ) ; T . TVar ( a6 ) ] , T . TVar ( a6 ) ) ; ;
let t6 = T . Arrow ( T . TVar ( a6 ) , T . TVar ( a5 ) ) ; ;
module Tp = Unify ; ;
module Main ( C : V1_LWT . CONSOLE ) ( S : V1_LWT . STACKV4 ) = struct module Session = Session . Tcp ( S ) let horseos = Horse_manager . create let start c s = let log message = C . log c message in let rec listen_input session username = Session . read session ( Horse_manager . broadcast_message horseos username ) >> listen_input session username in let rec relay_messages session = Horse_manager . wait_for_messages horseos >>= fun message -> Session . write session message >> relay_messages session in let write_userinfo session = Session . write session ( Horse_manager . get_userinfo horseos ) in let main session_initial = Session . read session_initial ( fun username -> if Horse_manager . user_exists horseos username then Session . write session_initial ( Printf . sprintf " There ' s already a user called % s please try again . \ n " username ) >> Session . close session_initial " bad username " else ( let on_close reason = log ( Printf . sprintf " % s has quit ( % s ) \ n " username reason ) ; Horse_manager . remove_user horseos username in let session = Session . on_close session_initial on_close in log ( Printf . sprintf " % s joined " username ) ; Horse_manager . add_user horseos username ; write_userinfo session >> join [ listen_input session username ; relay_messages session ] ) ) in log " HorseOS is starting . " ; S . listen_tcpv4 s ~ port : 4444 ( fun flow -> let dst , dst_port = S . TCPV4 . get_dest flow in let message = Printf . sprintf ( " Got a connection from % s on port % d " ) ( Ipaddr . V4 . to_string dst ) dst_port in log message ; let session_initial = Session . of_flow flow in Session . write session_initial Horse_greeter . ascii >> main session_initial ) ; S . listen s ; end
module type Type = sig type mapping val read_map : mapping -> int -> int type mapping_rw val create_mapping_rw : int -> mapping_rw val mapping_rw_to_ro : mapping_rw -> mapping val add_mapping : mapping_rw -> int -> int -> unit type t = { enc_to_ucs : mapping ; ucs_to_enc : mapping ; } type rw = { rw_enc_to_ucs : mapping_rw ; rw_ucs_to_enc : mapping_rw ; } val create_rw : int -> int -> rw val add : rw -> int -> int -> unit val rw_to_ro : rw -> t val no_char_ucs : t -> int val no_char_enc : t -> int val enc_to_ucs : t -> int -> int val ucs_to_enc : t -> int -> int val of_name : string -> t end
module Make ( Config : ConfigInt . Type ) Type : Type = struct type mapping = { no_char : int ; tbl : Tbl31 . Bytes . t } t let read_map map i = Tbl31 . Bytes . get map . tbl i type mapping_rw = { rw_no_char : int ; mutable rw_tbl : int IMap . t } t let create_mapping_rw no_char = { rw_no_char = no_char ; rw_tbl = IMap . empty } empty let mapping_rw_to_ro rw = { no_char = rw . rw_no_char ; tbl = Tbl31 . Bytes . of_map rw . rw_no_char rw . rw_tbl } rw_tbl let add_mapping map i n = map . rw_tbl <- IMap . add i n map . rw_tbl type t = { enc_to_ucs : mapping ; ucs_to_enc : mapping } mapping type rw = { rw_enc_to_ucs : mapping_rw ; rw_ucs_to_enc : mapping_rw } mapping_rw let create_rw unused_enc unused_ucs = { rw_enc_to_ucs = create_mapping_rw unused_ucs ; rw_ucs_to_enc = create_mapping_rw unused_enc } unused_enc let add map enc ucs = add_mapping map . rw_enc_to_ucs enc ucs ; add_mapping map . rw_ucs_to_enc ucs enc let rw_to_ro map = { enc_to_ucs = mapping_rw_to_ro map . rw_enc_to_ucs ; ucs_to_enc = mapping_rw_to_ro map . rw_ucs_to_enc } rw_ucs_to_enc let no_char_ucs map = map . enc_to_ucs . no_char let no_char_enc map = map . ucs_to_enc . no_char let enc_to_ucs map enc = read_map map . enc_to_ucs enc let ucs_to_enc map ucs = read_map map . ucs_to_enc ucs let loaded = Hashtbl . create 0 let of_name name : t = try let b = Hashtbl . find loaded name in match Weak . get b 0 with None -> Hashtbl . remove loaded name ; raise Not_found | Some x -> x with Not_found -> let map = Database . read Config . unimapdir " mar " input_value name in let b = Weak . create 1 in Weak . set b 0 ( Some map ) map ; Hashtbl . add loaded name b ; map end
module Spec = struct include Analyses . DefaultSpec module Addr = ValueDomain . Addr module D = ValueDomain . AddrSetDomain module C = ValueDomain . AddrSetDomain type trans_in = D . t type trans_out = D . t type transfer = trans_in -> trans_out let name ( ) = " uninit " let should_join x y = D . equal x y let startstate v : D . t = D . empty ( ) let threadenter ctx lval f args = [ D . empty ( ) ] let threadspawn ctx lval f args fctx = ctx . local let exitstate v : D . t = D . empty ( ) let rec conv_offset x = match x with | ` NoOffset -> ` NoOffset | ` Index ( Const ( CInt ( i , ik , s ) ) , o ) -> ` Index ( IntDomain . of_const ( i , ik , s ) , conv_offset o ) | ` Index ( _ , o ) -> ` Index ( IdxDom . top ( ) , conv_offset o ) | ` Field ( f , o ) -> ` Field ( f , conv_offset o ) let access_address ( ask : Queries . ask ) write lv = match ask . f ( Queries . MayPointTo ( AddrOf lv ) ) with | a when not ( Queries . LS . is_top a ) -> let to_extra ( v , o ) xs = ( v , Base . Offs . from_offset ( conv_offset o ) , write ) :: xs in Queries . LS . fold to_extra a [ ] | _ -> M . warn " Access to unknown address could be global " ; [ ] let rec access_one_byval a rw ( exp : exp ) = match exp with | Const _ -> [ ] | Lval lval -> access_address a rw lval @ ( access_lv_byval a lval ) | BinOp ( op , arg1 , arg2 , typ ) -> let a1 = access_one_byval a rw arg1 in let a2 = access_one_byval a rw arg2 in a1 @ a2 | UnOp ( op , arg1 , typ ) -> access_one_byval a rw arg1 | AddrOf lval -> access_lv_byval a lval | StartOf lval -> access_lv_byval a lval | CastE ( t , exp ) -> access_one_byval a rw exp | _ -> [ ] and access_lv_byval a ( lval : lval ) = let rec access_offset ( ofs : offset ) = match ofs with | NoOffset -> [ ] | Field ( fld , ofs ) -> access_offset ofs | Index ( exp , ofs ) -> access_one_byval a false exp @ access_offset ofs in match lval with | Var x , ofs -> access_offset ofs | Mem n , ofs -> access_one_byval a false n @ access_offset ofs let varoffs a ( rval : exp ) = let f vs ( v , o , _ ) = ( v , o ) :: vs in List . fold_left f [ ] ( access_one_byval a false rval ) let vars a ( rval : exp ) : Addr . t list = List . map Addr . from_var_offset ( varoffs a rval ) let is_prefix_of ( v1 , ofs1 : varinfo * ( Addr . field , Addr . idx ) Lval . offs ) ( v2 , ofs2 : varinfo * ( Addr . field , Addr . idx ) Lval . offs ) : bool = let rec is_offs_prefix_of pr os = match ( pr , os ) with | ( ` NoOffset , _ ) -> true | ( ` Field ( f1 , o1 ) , ` Field ( f2 , o2 ) ) -> CilType . Fieldinfo . equal f1 f2 && is_offs_prefix_of o1 o2 | ( _ , _ ) -> false in CilType . Varinfo . equal v1 v2 && is_offs_prefix_of ofs1 ofs2 let is_expr_initd a ( expr : exp ) ( st : D . t ) : bool = let variables = vars a expr in let raw_vars = List . filter_map Addr . to_var_offset variables in let will_addr_init ( t : bool ) a = let f addr = GobOption . exists ( is_prefix_of a ) ( Addr . to_var_offset addr ) in if D . exists f st then begin Messages . warn " Uninitialized variable % a accessed . " Addr . pretty ( Addr . from_var_offset a ) ; false end else t in List . fold_left will_addr_init true raw_vars let remove_if_prefix ( pr : varinfo * ( Addr . field , Addr . idx ) Lval . offs ) ( uis : D . t ) : D . t = let f ad = let vals = Addr . to_var_offset ad in GobOption . for_all ( fun a -> not ( is_prefix_of pr a ) ) vals in D . filter f uis type lval_offs = ( Addr . field , Addr . idx ) Lval . offs type var_offs = varinfo * lval_offs let rec get_pfx ( v : varinfo ) ( cx : lval_offs ) ( ofs : lval_offs ) ( target : typ ) ( other : typ ) : var_offs list = let rec cat o i = match o with | ` NoOffset -> i | ` Field ( f , o ) -> ` Field ( f , cat o i ) | ` Index ( v , o ) -> ` Index ( v , cat o i ) in let rec rev lo = match lo with | ` NoOffset -> ` NoOffset | ` Field ( f , o ) -> cat ( rev o ) ( ` Field ( f , ` NoOffset ) ) | ` Index ( v , o ) -> cat ( rev o ) ( ` Index ( v , ` NoOffset ) ) in let rec bothstruct ( t : fieldinfo list ) ( tf : fieldinfo ) ( o : fieldinfo list ) ( no : lval_offs ) : var_offs list = match t , o with | x :: xs , y :: ys when CilType . Fieldinfo . equal x tf -> get_pfx v ( ` Field ( y , cx ) ) no x . ftype y . ftype | x :: xs , y :: ys when CilType . Typ . equal x . ftype y . ftype -> bothstruct xs tf ys no | x :: xs , y :: ys -> [ ] | _ -> M . warn " Failed to analyze union at point % a -- did not find % s " Addr . pretty ( Addr . from_var_offset ( v , rev cx ) ) tf . fname ; [ ] in let utar , uoth = unrollType target , unrollType other in match ofs , utar , uoth with | ` NoOffset , _ , _ when utar == uoth -> [ v , rev cx ] | ` NoOffset , _ , TComp ( c2 , _ ) when not c2 . cstruct -> List . concat ( List . rev_map ( fun oth_f -> get_pfx v ( ` Field ( oth_f , cx ) ) ofs utar oth_f . ftype ) c2 . cfields ) | ` NoOffset , _ , _ -> [ ] | ` Index ( i , o ) , TArray ( t1 , _ , _ ) , TArray ( t2 , _ , _ ) -> get_pfx v ( ` Index ( i , cx ) ) o t1 t2 | ` Index ( i , o ) , _ , TComp ( c2 , _ ) when not c2 . cstruct -> List . concat ( List . rev_map ( fun oth_f -> get_pfx v ( ` Field ( oth_f , cx ) ) ofs utar oth_f . ftype ) c2 . cfields ) | ` Field ( f , o ) , TComp ( c1 , _ ) , TComp ( c2 , _ ) when c1 . cstruct && c2 . cstruct -> bothstruct c1 . cfields f c2 . cfields o | ` Field ( f , o ) , TComp ( c1 , _ ) , _ when not c1 . cstruct -> get_pfx v cx o f . ftype uoth | ` Field ( f , o ) , TComp ( c1 , _ ) , TComp ( c2 , _ ) when c1 . cstruct && not c2 . cstruct -> List . concat ( List . rev_map ( fun oth_f -> get_pfx v ( ` Field ( oth_f , cx ) ) ofs utar oth_f . ftype ) c2 . cfields ) | _ -> M . warn " Failed to analyze union at point % a " Addr . pretty ( Addr . from_var_offset ( v , rev cx ) ) ; [ ] let init_lval ( a : Queries . ask ) ( lv : lval ) ( st : D . t ) : D . t = let init_vo ( v : varinfo ) ( ofs : lval_offs ) : D . t = List . fold_right remove_if_prefix ( get_pfx v ` NoOffset ofs v . vtype v . vtype ) st in match a . f ( Queries . MayPointTo ( AddrOf lv ) ) with | a when Queries . LS . cardinal a = 1 -> begin let var , ofs = Queries . LS . choose a in init_vo var ( conv_offset ofs ) end | _ -> st let to_addrs ( v : varinfo ) : Addr . t list = let make_offs = List . fold_left ( fun o f -> ` Field ( f , o ) ) ` NoOffset in let rec add_fields ( base : Addr . field list ) fs acc = match fs with | [ ] -> acc | f :: fs -> match unrollType f . ftype with | TComp ( { cfields = ffs ; _ } , _ ) -> add_fields base fs ( List . rev_append ( add_fields ( f :: base ) ffs [ ] ) acc ) | _ -> add_fields base fs ( ( Addr . from_var_offset ( v , make_offs ( f :: base ) ) ) :: acc ) in match unrollType v . vtype with | TComp ( { cfields = fs ; _ } , _ ) -> add_fields [ ] fs [ ] | _ -> [ Addr . from_var v ] let remove_unreachable ( ask : Queries . ask ) ( args : exp list ) ( st : D . t ) : D . t = let reachable = let do_exp e = match ask . f ( Queries . ReachableFrom e ) with | a when not ( Queries . LS . is_top a ) -> let to_extra ( v , o ) xs = AD . from_var_offset ( v , ( conv_offset o ) ) :: xs in Queries . LS . fold to_extra ( Queries . LS . remove ( dummyFunDec . svar , ` NoOffset ) a ) [ ] | _ -> [ ] in List . concat_map do_exp args in let add_exploded_struct ( one : AD . t ) ( many : AD . t ) : AD . t = let vars = AD . to_var_may one in List . fold_right AD . add ( List . concat_map to_addrs vars ) many in let vars = List . fold_right add_exploded_struct reachable ( AD . empty ( ) ) in if D . is_top st then D . top ( ) else D . filter ( fun x -> AD . mem x vars ) st let assign ctx ( lval : lval ) ( rval : exp ) : trans_out = ignore ( is_expr_initd ( Analyses . ask_of_ctx ctx ) rval ctx . local ) ; init_lval ( Analyses . ask_of_ctx ctx ) lval ctx . local let branch ctx ( exp : exp ) ( tv : bool ) : trans_out = ignore ( is_expr_initd ( Analyses . ask_of_ctx ctx ) exp ctx . local ) ; ctx . local let body ctx ( f : fundec ) : trans_out = let add_var st v = List . fold_right D . add ( to_addrs v ) st in List . fold_left add_var ctx . local f . slocals let return ctx ( exp : exp option ) ( f : fundec ) : trans_out = let remove_var x v = List . fold_right D . remove ( to_addrs v ) x in let nst = List . fold_left remove_var ctx . local ( f . slocals @ f . sformals ) in match exp with | Some exp -> ignore ( is_expr_initd ( Analyses . ask_of_ctx ctx ) exp ctx . local ) ; nst | _ -> nst let enter ctx ( lval : lval option ) ( f : fundec ) ( args : exp list ) : ( D . t * D . t ) list = let nst = remove_unreachable ( Analyses . ask_of_ctx ctx ) args ctx . local in [ ctx . local , nst ] let combine ctx ( lval : lval option ) fexp ( f : fundec ) ( args : exp list ) fc ( au : D . t ) : trans_out = ignore ( List . map ( fun x -> is_expr_initd ( Analyses . ask_of_ctx ctx ) x ctx . local ) args ) ; let cal_st = remove_unreachable ( Analyses . ask_of_ctx ctx ) args ctx . local in let ret_st = D . union au ( D . diff ctx . local cal_st ) in match lval with | None -> ret_st | Some lv -> init_lval ( Analyses . ask_of_ctx ctx ) lv ret_st let special ctx ( lval : lval option ) ( f : varinfo ) ( arglist : exp list ) : D . t = match lval with | Some lv -> init_lval ( Analyses . ask_of_ctx ctx ) lv ctx . local | _ -> ctx . local ) * end
let _ = MCP . register_analysis ( module Spec : MCPSpec )
module NameAccessSet = Set . Make ( Define . NameAccess )
module AccessCollector = struct let rec from_expression collected { Node . value ; location = expression_location } = let open Expression in let from_entry collected { Dictionary . Entry . key ; value } = let collected = from_expression collected key in from_expression collected value in match value with | Lambda { Lambda . parameters ; body } -> let collected = let from_parameter collected { Node . value = { Parameter . value ; _ } ; _ } = Option . value_map value ~ f ( : from_expression collected ) ~ default : collected in List . fold parameters ~ init : collected ~ f : from_parameter in let bound_names = List . map parameters ~ f ( : fun { Node . value = { Parameter . name ; _ } ; _ } -> Identifier . split_star name |> snd ) |> Identifier . Set . of_list in let names_in_body = from_expression NameAccessSet . empty body in let unbound_names_in_body = Set . filter names_in_body ~ f ( : fun { Define . NameAccess . name ; _ } -> not ( Identifier . Set . mem bound_names name ) ) in Set . union unbound_names_in_body collected | Name ( Name . Identifier identifier ) -> Set . add collected { Define . NameAccess . name = identifier ; location = expression_location } | Name ( Name . Attribute _ ) -> collected | Await await -> from_expression collected await | BooleanOperator { BooleanOperator . left ; right ; _ } | ComparisonOperator { ComparisonOperator . left ; right ; _ } -> let collected = from_expression collected left in from_expression collected right | Call { Call . callee ; arguments } -> let collected = from_expression collected callee in List . fold arguments ~ init : collected ~ f ( : fun collected { Call . Argument . value ; _ } -> from_expression collected value ) | Dictionary { Dictionary . entries ; keywords } -> let collected = List . fold entries ~ init : collected ~ f : from_entry in List . fold keywords ~ init : collected ~ f : from_expression | DictionaryComprehension comprehension -> from_comprehension from_entry collected comprehension | Generator comprehension | ListComprehension comprehension | SetComprehension comprehension -> from_comprehension from_expression collected comprehension | List expressions | Set expressions | Tuple expressions -> List . fold expressions ~ init : collected ~ f : from_expression | FormatString substrings -> let from_substring sofar = function | Substring . Literal _ -> sofar | Substring . Format expression -> from_expression sofar expression in List . fold substrings ~ init : collected ~ f : from_substring | Starred ( Starred . Once expression ) | Starred ( Starred . Twice expression ) -> from_expression collected expression | Ternary { Ternary . target ; test ; alternative } -> let collected = from_expression collected target in let collected = from_expression collected test in from_expression collected alternative | UnaryOperator { UnaryOperator . operand ; _ } -> from_expression collected operand | WalrusOperator { WalrusOperator . value ; _ } -> from_expression collected value | Yield yield -> Option . value_map yield ~ default : collected ~ f ( : from_expression collected ) | YieldFrom yield -> from_expression collected yield | Constant _ -> collected and from_comprehension : ' a . ( NameAccessSet . t -> ' a -> NameAccessSet . t ) -> NameAccessSet . t -> ' a Comprehension . t -> NameAccessSet . t = fun from_element collected { Comprehension . element ; generators } -> let remove_bound_names ~ bound_names = Set . filter ~ f ( : fun { Define . NameAccess . name ; _ } -> not ( Identifier . Set . mem bound_names name ) ) in let bound_names , collected = let from_generator ( bound_names , accesses_sofar ) { Comprehension . Generator . target ; iterator ; conditions ; _ } = let iterator_accesses = from_expression NameAccessSet . empty iterator |> remove_bound_names ~ bound_names in let bound_names = let add_bound_name bound_names { Define . NameAccess . name ; _ } = Set . add bound_names name in from_expression NameAccessSet . empty target |> NameAccessSet . fold ~ init : bound_names ~ f : add_bound_name in let condition_accesses = List . fold conditions ~ init : NameAccessSet . empty ~ f : from_expression |> remove_bound_names ~ bound_names in ( bound_names , NameAccessSet . union_list [ accesses_sofar ; iterator_accesses ; condition_accesses ] ) in List . fold generators ~ init ( : Identifier . Set . empty , collected ) ~ f : from_generator in let element_accesses = from_element NameAccessSet . empty element |> remove_bound_names ~ bound_names in NameAccessSet . union collected element_accesses end
let extract_reads_in_expression expression = let name_access_to_identifier_node { Define . NameAccess . name ; location } = { Node . value = name ; location } in AccessCollector . from_expression NameAccessSet . empty expression |> NameAccessSet . to_list |> List . map ~ f : name_access_to_identifier_node
let extract_reads_in_statement { Node . value ; _ } = let expressions = match value with | Statement . Assign { Assign . value = expression ; _ } | Expression expression | If { If . test = expression ; _ } | While { While . test = expression ; _ } -> [ expression ] | Delete expressions -> expressions | Assert { Assert . test ; message ; _ } -> [ test ] @ Option . to_list message | For { For . target ; iterator ; _ } -> [ target ; iterator ] | Raise { Raise . expression ; from } -> Option . to_list expression @ Option . to_list from | Return { Return . expression ; _ } -> Option . to_list expression | With { With . items ; _ } -> items |> List . map ~ f ( : fun ( value , _ ) -> value ) | Break | Class _ | Continue | Define _ | Global _ | Import _ | Match _ | Nonlocal _ | Pass | Try _ -> [ ] in expressions |> List . concat_map ~ f : extract_reads_in_expression
type defined_locals = Scope . Binding . t Identifier . Map . t
let create_map = List . fold ~ init : Identifier . Map . empty ~ f ( : fun sofar ( { Scope . Binding . name ; _ } as binding ) -> Map . set sofar ~ key ( : Identifier . sanitized name ) ~ data : binding )
module type Context = sig val fixpoint_post_statement : ( Statement . t * defined_locals ) StatementKey . Table . t end
module State ( Context : Context ) = struct type t = | Bottom | Value of defined_locals let show = function | Bottom -> " [ ] " | Value state -> let show_binding { Scope . Binding . name ; location ; _ } = [ % show : Identifier . t * Location . t ] ( name , location ) in state |> Map . data |> List . map ~ f : show_binding |> String . concat ~ sep " , : " |> Format . sprintf " [ % s ] " let bottom = Bottom let pp format state = Format . fprintf format " % s " ( show state ) let initial ~ define { : Node . value = { Define . signature ; _ } ; _ } = signature . parameters |> Scope . Binding . of_parameters [ ] |> create_map |> fun value -> Value value let less_or_equal ~ left ~ right = match left , right with | Value left , Value right -> let to_set map = Map . keys map |> Identifier . Set . of_list in to_set right |> Set . is_subset ~ of_ ( : to_set left ) | Value _ , Bottom -> false | Bottom , Value _ -> true | Bottom , Bottom -> true let join left right = match left , right with | Value left , Value right -> let intersect ~ key : _ = function | ` Both ( left , _ ) -> Some left | ` Right _ | ` Left _ -> None in Value ( Map . merge ~ f : intersect left right ) | Value left , Bottom -> Value left | Bottom , Value right -> Value right | Bottom , Bottom -> Bottom let widen ~ previous ~ next ~ iteration : _ = join previous next let forward ~ statement_key state ~ statement = match state with | Bottom -> Bottom | Value state -> let union ~ key : _ = function | ` Both ( ( { Scope . Binding . location = left_location ; _ } as left ) , ( { Scope . Binding . location = right_location ; _ } as right ) ) -> if [ % compare : Location . t ] left_location right_location >= 0 then Some left else Some right | ` Right only | ` Left only -> Some only in let new_state = Scope . Binding . of_statement [ ] statement |> create_map |> Map . merge ~ f : union state in Hashtbl . set Context . fixpoint_post_statement ~ key : statement_key ~ data ( : statement , new_state ) ; Value new_state let backward ~ statement_key : _ _ ~ statement : _ = failwith " Not implemented " end
let defined_locals_at_each_statement define = let module Context = struct let fixpoint_post_statement = StatementKey . Table . create ( ) end in let module State = State ( Context ) in let module Fixpoint = Fixpoint . Make ( State ) in let cfg = Cfg . create ( Node . value define ) in let fixpoint = Fixpoint . forward ~ cfg ~ initial ( : State . initial ~ define ) in let defined_locals = match Context . fixpoint_post_statement |> StatementKey . Table . to_alist |> StatementKey . Map . of_alist with | ` Ok map -> map | ` Duplicate_key _ -> StatementKey . Map . empty in Fixpoint . exit fixpoint >>| ( fun _ -> defined_locals ) |> Option . value ~ default : StatementKey . Map . empty
let errors ~ qualifier ~ define defined_locals_at_each_statement = let emit_error { Node . value ; location } = Error . create ~ location ( : Location . with_module ~ module_reference : qualifier location ) ~ kind ( : Error . UninitializedLocal value ) ~ define in let all_locals = let { Scope . Scope . bindings ; globals ; nonlocals ; _ } = Scope . Scope . of_define_exn define . value in let locals = Identifier . Map . keys bindings |> List . map ~ f : Identifier . sanitized |> Identifier . Set . of_list in let globals = Identifier . Set . map ~ f : Identifier . sanitized globals in let nonlocals = Identifier . Set . map ~ f : Identifier . sanitized nonlocals in Identifier . Set . diff ( Identifier . Set . diff locals globals ) nonlocals in let in_local_scope { Node . value = identifier ; _ } = identifier |> Identifier . sanitized |> Identifier . Set . mem all_locals in let uninitialized_usage ( statement , initialized ) = let is_uninitialized { Node . value = identifier ; _ } = not ( Map . mem initialized ( Identifier . sanitized identifier ) ) in extract_reads_in_statement statement |> List . filter ~ f : is_uninitialized in defined_locals_at_each_statement |> Map . data |> List . concat_map ~ f : uninitialized_usage |> List . filter ~ f : in_local_scope |> List . map ~ f : emit_error
let run_on_define ~ qualifier define = defined_locals_at_each_statement define |> errors ~ qualifier ~ define
let run ~ configuration : _ ~ environment : _ ~ source ( { : Source . source_path = { ModulePath . qualifier ; _ } ; _ } as source ) = source |> Preprocessing . defines ~ include_toplevels : false |> List . map ~ f ( : run_on_define ~ qualifier ) |> List . concat
let assert_uninitialized_errors ~ context = let check ~ configuration ~ environment ~ source = UninitializedLocalCheck . run ~ configuration ~ environment ( : TypeEnvironment . read_only environment ) ~ source in assert_errors ~ context ~ check
let test_simple context = let assert_uninitialized_errors = assert_uninitialized_errors ~ context in assert_uninitialized_errors { | def f ( ) : x = y y = 5 } | [ " Uninitialized local [ 61 ] : Local variable ` y ` is undefined , or not always defined . " ] ; assert_uninitialized_errors { | def f ( y ) : x = y y = 5 } | [ ] ; assert_uninitialized_errors { | def f ( x ) : if x > 5 : return y # Error y = 5 z = 5 return z # OK } | [ " Uninitialized local [ 61 ] : Local variable ` y ` is undefined , or not always defined . " ] ; assert_uninitialized_errors { | def f ( x ) : if x > 5 : y = 2 return y } | [ " Uninitialized local [ 61 ] : Local variable ` y ` is undefined , or not always defined . " ] ; assert_uninitialized_errors { | def f ( ) -> int : try : bad = 0 / 0 x = 1 # ` x ` is defined here except ZeroDivisionError : return x } | [ " Uninitialized local [ 61 ] : Local variable ` x ` is undefined , or not always defined . " ] ; assert_uninitialized_errors { | x , y , z = 0 , 0 , 0 def access_global ( ) -> int : global y _ = x # Refers to local ` x ` , hence error x = 1 _ = y # Refers to global ` y ` , explictly specified y = 1 _ = z # Refers to global ` z ` , implicitly } | [ " Uninitialized local [ 61 ] : Local variable ` x ` is undefined , or not always defined . " ] ; assert_uninitialized_errors { | class Foo ( object ) : pass def f ( ) : return Foo ( ) } | [ ] ; assert_uninitialized_errors { | def f ( ) : def g ( ) : pass g ( ) } | [ ] ; assert_uninitialized_errors { | def f ( ) : x , y = 0 , 0 return x , y } | [ ] ; assert_uninitialized_errors { | def f ( * args , ** kwargs ) -> None : print ( args ) print ( list ( kwargs . items ( ) ) ) } | [ ] ; assert_uninitialized_errors { | x = 0 def f ( ) -> None : global x if x == 0 : x = 1 } | [ ] ; assert_uninitialized_errors { | def f ( x : str ) -> None : assert True , x } | [ ] ; assert_uninitialized_errors { | from media import something def f ( ) : something ( ) media = 1 } | [ ] ; assert_uninitialized_errors { | def f ( ) : ( x := 0 ) } | [ ] ; assert_uninitialized_errors { | def f ( ) : ( ( x := 0 ) and ( y := x ) ) } | [ ] ; assert_uninitialized_errors { | def f ( ) : ( ( y := x ) and ( x := 0 ) ) } | [ ] ; assert_uninitialized_errors { | def f ( ) : [ y for x in [ 1 , 2 , 3 ] if ( y := x ) > 2 ] } | [ ] ; assert_uninitialized_errors { | def f ( ) : _ = x . field x = Foo ( ) } | [ ] ; assert_uninitialized_errors { | def f ( ) : with open ( " x " ) as x : pass _ = x , y x , y = None , None } | [ " Uninitialized local [ 61 ] : Local variable ` y ` is undefined , or not always defined . " ] ; assert_uninitialized_errors { | def f ( ) : y = [ x for x in x ] x = [ ] } | [ " Uninitialized local [ 61 ] : Local variable ` x ` is undefined , or not always defined . " ] ; assert_uninitialized_errors { | def f ( ) : _ = [ ( x , y ) for x , y in [ ] ] x = None _ = x , y y = None } | [ " Uninitialized local [ 61 ] : Local variable ` y ` is undefined , or not always defined . " ] ; ( )
let test_cfg context = let assert_uninitialized_errors = assert_uninitialized_errors ~ context in assert_uninitialized_errors { | def f ( ) : if True : x = 1 else : raise AssertionError ( " error " ) return x def g ( ) : if True : y = 1 else : assert False , " error " return y def h ( ) : if True : z = 1 else : assert True , " error " return z } | [ " Uninitialized local [ 61 ] : Local variable ` z ` is undefined , or not always defined . " ] ; assert_uninitialized_errors { | def baz ( ) -> int : while True : b = 1 break return b } | [ ] ; assert_uninitialized_errors { | def f ( ) : try : x = 1 except Exception : x = 2 finally : print ( x ) } | [ ] ; assert_uninitialized_errors { | def f ( ) : try : x = 1 return finally : print ( x ) } | [ " Uninitialized local [ 61 ] : Local variable ` x ` is undefined , or not always defined . " ] ; assert_uninitialized_errors { | def f ( ) : try : return ( x := 1 ) finally : print ( x ) } | [ " Uninitialized local [ 61 ] : Local variable ` x ` is undefined , or not always defined . " ] ; assert_uninitialized_errors { | def may_raise ( ) -> bool : if 1 > 2 : raise Exception ( ) else : return True def f ( ) -> bool : try : x = may_raise ( ) return x finally : print ( x ) } | [ " Uninitialized local [ 61 ] : Local variable ` x ` is undefined , or not always defined . " ] ; ( )
let assert_defined_locals source expected = let define = parse_single_define source in let open Statement in let open Expression in let open UninitializedLocalCheck in let actual_defined_locals = define |> Node . create_with_default_location |> defined_locals_at_each_statement in let sanitize_for_tests statement = let with_dummy_assert_origin = function | { Node . value = Statement . Assert assert_ ; _ } as statement -> { statement with Node . value = Statement . Assert { assert_ with origin = Assertion } } | other -> other in let make_dunder_attribute_special = function | Expression . Name ( Attribute ( { attribute = " __enter__ " | " __next__ " | " __iter__ " ; _ } as attribute ) ) -> Expression . Name ( Attribute { attribute with special = true } ) | other -> other in with_dummy_assert_origin statement |> Node . map ~ f ( : Transform . transform_expressions ~ transform : make_dunder_attribute_special ) in let item_equal ( left_statement , left_identifiers ) ( right_statement , right_identifiers ) = Statement . location_insensitive_compare ( sanitize_for_tests left_statement ) ( sanitize_for_tests right_statement ) = 0 && [ % compare . equal : ( Identifier . t * Location . t ) list ] left_identifiers right_identifiers in let parse_statement_and_locals ( statement_string , locals_with_locations ) = ( parse_single_statement statement_string , List . map locals_with_locations ~ f ( : fun ( local , location ) -> local , parse_location location ) ) in let actual = let extract_name_and_location ( _key , ( statement , identifier_to_binding ) ) = ( statement , Map . data identifier_to_binding |> List . map ~ f ( : fun { Scope . Binding . name ; location ; _ } -> name , location ) ) in Map . to_alist actual_defined_locals |> List . map ~ f : extract_name_and_location in assert_equal ~ cmp ( : List . equal item_equal ) ~ printer [ :% show : ( Statement . t * ( Identifier . t * Location . t ) list ) list ] ( expected |> List . map ~ f : parse_statement_and_locals ) actual
let test_defined_locals_at_each_statement _ = assert_defined_locals { | def f ( ) : if True : x = 1 else : raise AssertionError ( " error " ) return x } | [ { | x = 1 } , | [ " x " , " 4 : 4 - 4 : 5 " ] ; { | raise AssertionError ( " error " ) } , | [ ] ; { | assert True } , | [ ] ; { | return x } , | [ " x " , " 4 : 4 - 4 : 5 " ] ; { | assert False } , | [ ] ; ] ; assert_defined_locals { | def f ( ) : x = y y = 5 } | [ { | y = 5 } , | [ " x " , " 3 : 2 - 3 : 3 " ; " y " , " 4 : 2 - 4 : 3 " ] ; { | x = y } , | [ " x " , " 3 : 2 - 3 : 3 " ] ] ; assert_defined_locals { | def f ( y ) : x = y y = 5 } | [ { | y = 5 } , | [ " x " , " 3 : 2 - 3 : 3 " ; " y " , " 4 : 2 - 4 : 3 " ] ; { | x = y } , | [ " x " , " 3 : 2 - 3 : 3 " ; " y " , " 2 : 6 - 2 : 7 " ] ] ; assert_defined_locals { | def f ( x ) : if x > 5 : return y y = 5 z = 5 return z } | [ { | return z } , | [ " x " , " 2 : 6 - 2 : 7 " ; " y " , " 5 : 2 - 5 : 3 " ; " z " , " 6 : 2 - 6 : 3 " ] ; { | z = 5 } , | [ " x " , " 2 : 6 - 2 : 7 " ; " y " , " 5 : 2 - 5 : 3 " ; " z " , " 6 : 2 - 6 : 3 " ] ; { | return y } , | [ " x " , " 2 : 6 - 2 : 7 " ] ; { | assert x > 5 } , | [ " x " , " 2 : 6 - 2 : 7 " ] ; { | y = 5 } , | [ " x " , " 2 : 6 - 2 : 7 " ; " y " , " 5 : 2 - 5 : 3 " ] ; { | assert x <= 5 } , | [ " x " , " 2 : 6 - 2 : 7 " ] ; ] ; assert_defined_locals { | def f ( x ) : if x > 5 : y = 2 return y } | [ { | y = 2 } , | [ " x " , " 2 : 6 - 2 : 7 " ; " y " , " 4 : 4 - 4 : 5 " ] ; { | assert x > 5 } , | [ " x " , " 2 : 6 - 2 : 7 " ] ; { | return y } , | [ " x " , " 2 : 6 - 2 : 7 " ] ; { | assert x <= 5 } , | [ " x " , " 2 : 6 - 2 : 7 " ] ; ] ; assert_defined_locals { | def f ( ) -> int : try : bad = 0 / 0 x = 1 except ZeroDivisionError : return x } | [ { | return x } , | [ ] ; { | x = 1 } , | [ " bad " , " 4 : 8 - 4 : 11 " ; " x " , " 5 : 8 - 5 : 9 " ] ; { | ZeroDivisionError } , | [ ] ; { | bad = 0 / 0 } , | [ " bad " , " 4 : 8 - 4 : 11 " ] ; ] ; assert_defined_locals { | def access_global ( ) -> int : global y _ = x # Refers to local ` x ` ( defined below ) x = 1 _ = y # Refers to global ` y ` y = 1 _ = z # Refers to global ` z ` } | [ { | x = 1 } , | [ " _ " , " 4 : 2 - 4 : 3 " ; " x " , " 5 : 2 - 5 : 3 " ] ; { | _ = z } , | [ " _ " , " 8 : 2 - 8 : 3 " ; " x " , " 5 : 2 - 5 : 3 " ; " y " , " 7 : 2 - 7 : 3 " ] ; { | _ = x } , | [ " _ " , " 4 : 2 - 4 : 3 " ] ; { | _ = y } , | [ " _ " , " 6 : 2 - 6 : 3 " ; " x " , " 5 : 2 - 5 : 3 " ] ; { | global y } , | [ ] ; { | y = 1 } , | [ " _ " , " 6 : 2 - 6 : 3 " ; " x " , " 5 : 2 - 5 : 3 " ; " y " , " 7 : 2 - 7 : 3 " ] ; ] ; assert_defined_locals { | def f ( ) : return Foo ( ) } | [ { | return Foo ( ) } , | [ ] ] ; assert_defined_locals { | def f ( ) : def g ( ) : pass g ( ) } | [ { | g ( ) } , | [ " g " , " 3 : 2 - 4 : 8 " ] ; { | def g ( ) : pass } , | [ " g " , " 3 : 2 - 4 : 8 " ] ] ; assert_defined_locals { | def f ( ) : x , y = 0 , 0 return x , y } | [ { | return ( x , y ) } , | [ " x " , " 3 : 2 - 3 : 3 " ; " y " , " 3 : 5 - 3 : 6 " ] ; { | x , y = 0 , 0 } , | [ " x " , " 3 : 2 - 3 : 3 " ; " y " , " 3 : 5 - 3 : 6 " ] ; ] ; assert_defined_locals { | def f ( * args , ** kwargs ) -> None : print ( args ) print ( list ( kwargs . items ( ) ) ) } | [ { | print ( list ( kwargs . items ( ) ) ) } , | [ " args " , " 2 : 8 - 2 : 12 " ; " kwargs " , " 2 : 16 - 2 : 22 " ] ; { | print ( args ) } , | [ " args " , " 2 : 8 - 2 : 12 " ; " kwargs " , " 2 : 16 - 2 : 22 " ] ; ] ; assert_defined_locals { | def f ( ) -> None : global x if x == 0 : x = 1 } | [ { | x = 1 } , | [ " x " , " 5 : 4 - 5 : 5 " ] ; { | assert x != 0 } , | [ ] ; { | assert x == 0 } , | [ ] ; { | global x } , | [ ] ; ] ; assert_defined_locals { | def f ( x : str ) -> None : assert True , x } | [ { | assert True , x } , | [ " x " , " 2 : 6 - 2 : 12 " ] ] ; assert_defined_locals { | def f ( ) : ( x := 0 ) } | [ { | ( x := 0 ) } , | [ " x " , " 3 : 3 - 3 : 4 " ] ] ; assert_defined_locals { | def f ( ) : ( ( x := 0 ) and ( y := x ) ) } | [ { | ( ( x := 0 ) and ( y := x ) ) } , | [ " x " , " 3 : 4 - 3 : 5 " ; " y " , " 3 : 17 - 3 : 18 " ] ] ; assert_defined_locals { | def f ( ) : ( ( y := x ) and ( x := 0 ) ) } | [ { | ( ( y := x ) and ( x := 0 ) ) } , | [ " x " , " 3 : 17 - 3 : 18 " ; " y " , " 3 : 4 - 3 : 5 " ] ] ; assert_defined_locals { | def f ( ) : [ y for x in [ 1 , 2 , 3 ] if ( y := x ) > 2 ] } | [ { | [ y for x in [ 1 , 2 , 3 ] if ( y := x ) > 2 ] } , | [ " y " , " 3 : 26 - 3 : 27 " ] ] ; assert_defined_locals { | def f ( ) : _ = x . field x = Foo ( ) } | [ { | x = Foo ( ) } , | [ " _ " , " 3 : 2 - 3 : 3 " ; " x " , " 4 : 2 - 4 : 3 " ] ; { | _ = x . field } , | [ " _ " , " 3 : 2 - 3 : 3 " ] ] ; assert_defined_locals { | def f ( ) : with open ( " x " , " 1 : 2 - 3 : 4 " ) as x : pass _ = x , y x , y = None , None } | [ { | x , y = None , None } , | [ " _ " , " 5 : 2 - 5 : 3 " ; " x " , " 6 : 2 - 6 : 3 " ; " y " , " 6 : 5 - 6 : 6 " ] ; { | pass } , | [ " x " , " 3 : 31 - 3 : 32 " ] ; { | _ = x , y } , | [ " _ " , " 5 : 2 - 5 : 3 " ; " x " , " 3 : 31 - 3 : 32 " ] ; { | x = open ( " x " , " 1 : 2 - 3 : 4 " ) . __enter__ ( ) } , | [ " x " , " 3 : 31 - 3 : 32 " ] ; ] ; assert_defined_locals { | def f ( ) : y = [ x for x in x ] x = [ ] } | [ { | x = [ ] } , | [ " x " , " 4 : 2 - 4 : 3 " ; " y " , " 3 : 2 - 3 : 3 " ] ; { | y = [ x for x in x ] } , | [ " y " , " 3 : 2 - 3 : 3 " ] ] ; assert_defined_locals { | def f ( ) : _ = [ ( x , y ) for x , y in [ ] ] x = None _ = x , y y = None } | [ { | _ = x , y } , | [ " _ " , " 5 : 2 - 5 : 3 " ; " x " , " 4 : 2 - 4 : 3 " ] ; { | x = None } , | [ " _ " , " 3 : 2 - 3 : 3 " ; " x " , " 4 : 2 - 4 : 3 " ] ; { | y = None } , | [ " _ " , " 5 : 2 - 5 : 3 " ; " x " , " 4 : 2 - 4 : 3 " ; " y " , " 6 : 2 - 6 : 3 " ] ; { | _ = [ ( x , y ) for x , y in [ ] ] } , | [ " _ " , " 3 : 2 - 3 : 3 " ] ; ] ; assert_defined_locals { | def f ( ) : if True : x = 1 else : raise AssertionError ( " error " ) return x } | [ { | x = 1 } , | [ " x " , " 4 : 4 - 4 : 5 " ] ; { | raise AssertionError ( " error " ) } , | [ ] ; { | assert True } , | [ ] ; { | return x } , | [ " x " , " 4 : 4 - 4 : 5 " ] ; { | assert False } , | [ ] ; ] ; assert_defined_locals { | def g ( ) : if True : y = 1 else : assert False , " error " return y } | [ { | y = 1 } , | [ " y " , " 4 : 4 - 4 : 5 " ] ; { | assert False , " error " } , | [ ] ; { | assert True } , | [ ] ; { | return y } , | [ " y " , " 4 : 4 - 4 : 5 " ] ; { | assert False } , | [ ] ; ] ; assert_defined_locals { | def h ( ) : if True : z = 1 else : assert True , " error " return z } | [ { | z = 1 } , | [ " z " , " 4 : 4 - 4 : 5 " ] ; { | assert True , " error " } , | [ ] ; { | assert True } , | [ ] ; { | return z } , | [ ] ; { | assert False } , | [ ] ; ] ; assert_defined_locals { | def baz ( ) -> int : while True : b = 1 break return b } | [ { | b = 1 } , | [ " b " , " 4 : 8 - 4 : 9 " ] ; { | assert True } , | [ ] ; { | break } , | [ " b " , " 4 : 8 - 4 : 9 " ] ; { | return b } , | [ " b " , " 4 : 8 - 4 : 9 " ] ; { | assert False } , | [ ] ; ] ; assert_defined_locals { | def f ( ) : try : x = 1 except Exception : x = 2 finally : print ( x ) } | [ { | x = 2 } , | [ " x " , " 6 : 4 - 6 : 5 " ] ; { | print ( x ) } , | [ " x " , " 4 : 4 - 4 : 5 " ] ; { | Exception } , | [ ] ; { | x = 1 } , | [ " x " , " 4 : 4 - 4 : 5 " ] ; ] ; assert_defined_locals { | def f ( ) : try : x = 1 return finally : print ( x ) } | [ { | return } , | [ " x " , " 4 : 4 - 4 : 5 " ] ; { | print ( x ) } , | [ ] ; { | x = 1 } , | [ " x " , " 4 : 4 - 4 : 5 " ] ] ; assert_defined_locals { | def f ( ) : try : return ( x := 1 ) finally : print ( x ) } | [ { | print ( x ) } , | [ ] ; { | return ( x := 1 ) } , | [ " x " , " 4 : 12 - 4 : 13 " ] ] ; assert_defined_locals { | def may_raise ( ) -> bool : if 1 > 2 : raise Exception ( ) else : return True } | [ { | raise Exception ( ) } , | [ ] ; { | return True } , | [ ] ; { | assert 1 > 2 } , | [ ] ; { | assert 1 <= 2 } , | [ ] ; ] ; assert_defined_locals { | def f ( ) -> bool : try : x = may_raise ( ) return x finally : print ( x ) } | [ { | return x } , | [ " x " , " 4 : 4 - 4 : 5 " ] ; { | print ( x ) } , | [ ] ; { | x = may_raise ( ) } , | [ " x " , " 4 : 4 - 4 : 5 " ] ] ; assert_defined_locals { | def foo ( x : str ) -> None : for x in [ 1 ] : print ( x ) print ( x , " outside " ) } | [ { | print ( x ) } , | [ " x " , " 3 : 6 - 3 : 7 " ] ; { | x = [ 1 ] . __iter__ ( ) . __next__ ( ) } , | [ " x " , " 3 : 6 - 3 : 7 " ] ; { | print ( x , " outside " ) } , | [ " x " , " 2 : 8 - 2 : 14 " ] ; ] ; ( )
let ( ) = " uninitializedCheck " >::: [ " simple " >:: test_simple ; " cfg " >:: test_cfg ; " defined_locals_at_each_statement " >:: test_defined_locals_at_each_statement ; ] |> Test . run
let ocaml_config = get_command_output " ocamlc - config "
let is_mingw = List . exists ( ( ) = " system : mingw " ) ocaml_config
let prefix = ref ( if is_mingw then begin let re = Str . regexp " : " in let conf = List . map ( fun l -> match Str . split re l with [ n ; v ] -> n , v | [ n ] -> n , " " | _ -> assert false ) ocaml_config in let lib = List . assoc " standard_library " conf in Filename . dirname lib end else " / usr / local " )
let ver_1_8_0 = ref false
let ext = if is_win32 then " . exe " else " "
let uninstall ( ) = if not is_win32 then begin if ! ver_1_8_0 then begin kprintf run " rm - vfr % s / share / pixmaps / ocamleditor " ! prefix ; kprintf run " rm - vf % s / bin / ocamleditor " ! prefix ; kprintf run " rm - vf % s / bin / oebuild % s " ! prefix ext ; kprintf run " rm - vf % s / bin / oebuild % s . opt " ! prefix ext ; end else begin kprintf run " rm - vfr % s / share / ocamleditor " ! prefix ; kprintf run " rm - vf % s / bin / ocamleditor " ! prefix ; kprintf run " rm - vf % s / bin / oebuild % s " ! prefix ext ; kprintf run " rm - vf % s / bin / oebuild % s . opt " ! prefix ext ; end end else prerr_endline " This script is not available under Windows " ; ;
let _ = main ~ default_target : uninstall ~ options [ : " - prefix " , Set_string prefix , ( sprintf " Installation prefix ( default is % s ) " ! prefix ) ; " - ver - 1 . 8 . 0 " , Set ver_1_8_0 , ( sprintf " Uninstall OCamlEditor version 1 . 8 . 0 " ) ;
module MyQuery = [ % graphql { | { dogOrHuman { . . . on Dog { name barkVolume } . . . on Human { name } } } } ] |
let pp formatter ( obj : qt ) = Format . fprintf formatter " < dogOrHuman = % a " > ( fun formatter -> function | ` FutureAddedValue _ -> Format . fprintf formatter " ` FutureAddedValue " | ` Dog ( dog : MyQuery . t_dogOrHuman_Dog ) -> Format . fprintf formatter " ` Dog [ @<>< name = % a ; barkVolume = % a ] " >@ Format . pp_print_string dog . name Format . pp_print_float dog . barkVolume | ` Human ( human : MyQuery . t_dogOrHuman_Human ) -> Format . fprintf formatter " ` Human [ @<>< name = % a ] " >@ Format . pp_print_string human . name ) obj . dogOrHuman
let equal ( a : qt ) ( b : qt ) = match ( a . dogOrHuman , b . dogOrHuman ) with | ` Dog a , ` Dog b -> a . name = b . name && a . barkVolume = b . barkVolume | ` Human a , ` Human b -> a . name = b . name | _ -> false
let decodes_exhaustive_query ( ) = test_exp ( { | { " dogOrHuman " : { " __typename " : " Dog " , " name " : " Fido " , " barkVolume " : 123 . 0 } } } | |> Json . Read . from_string |> MyQuery . unsafe_fromJson |> MyQuery . parse ) { dogOrHuman = ` Dog { name = " Fido " ; barkVolume = 123 . 0 } } equal pp
let tests = [ ( " Decodes exhaustive query " , decodes_exhaustive_query ) ]
let ml_declaration oc ud = if ud . ud_name = " " then fprintf oc " union_ % d =\ n " ud . ud_stamp else fprintf oc " % s =\ n " ( String . uncapitalize_ascii ud . ud_name ) ; let out_constr oc c = if c = " default " then if ud . ud_name <> " " then fprintf oc " Default_ % s " ud . ud_name else fprintf oc " Default_ % d " ud . ud_stamp else output_string oc ( String . capitalize_ascii c ) in let emit_case = function { case_labels = [ ] ; case_field = None } -> fprintf oc " | % a of int \ n " out_constr " default " | { case_labels = [ ] ; case_field = Some f } -> fprintf oc " | % a of int * % a \ n " out_constr " default " out_ml_type f . field_typ | { case_labels = lbls ; case_field = None } -> List . iter ( fun lbl -> fprintf oc " | % a \ n " out_constr lbl ) lbls | { case_labels = lbls ; case_field = Some f } -> List . iter ( fun lbl -> fprintf oc " | % a of % a \ n " out_constr lbl out_ml_type f . field_typ ) lbls in List . iter emit_case ud . ud_cases
let c_declaration oc ud = if ud . ud_cases = [ ] then fprintf oc " union % s ; \ n " ud . ud_name else begin out_union oc ud ; fprintf oc " ; \ n \ n " end
let declare_transl oc ud = fprintf oc " extern int camlidl_ml2c_ % s_union_ % s ( value , union % s , * camlidl_ctx _ctx ) ; \ n " ud . ud_mod ud . ud_name ud . ud_name ; fprintf oc " extern value camlidl_c2ml_ % s_union_ % s ( int , union % s , * camlidl_ctx _ctx ) ; \ n \ n " ud . ud_mod ud . ud_name ud . ud_name
let transl_ml_to_c oc ud = current_function := sprintf " union % s " ud . ud_name ; let v = new_var " _v " in let c = new_var " _c " in fprintf oc " int camlidl_ml2c_ % s_union_ % s ( value % s , union % s * % s , camlidl_ctx _ctx ) \ n " ud . ud_mod ud . ud_name v ud . ud_name c ; fprintf oc " { \ n " ; let pc = divert_output ( ) in increase_indent ( ) ; let discr = new_c_variable ( Type_int ( Int , Iunboxed ) ) in iprintf pc " % s = - 1 ; \ n " discr ; union_ml_to_c ml_to_c pc false Prefix . empty ud v ( sprintf "
let transl_c_to_ml oc ud = current_function := sprintf " union % s " ud . ud_name ; let discr = new_var " _discr " in let c = new_var " _c " in fprintf oc " value camlidl_c2ml_ % s_union_ % s ( int % s , union % s * % s , camlidl_ctx _ctx ) \ n " ud . ud_mod ud . ud_name discr ud . ud_name c ; fprintf oc " { \ n " ; let pc = divert_output ( ) in increase_indent ( ) ; let v = new_ml_variable ( ) in union_c_to_ml c_to_ml pc Prefix . empty ud ( sprintf "
let emit_transl oc ud = transl_ml_to_c oc ud ; transl_c_to_ml oc ud
module type HashedOrderedType = sig type t val equal : t -> t -> bool val hash : t -> int val compare : t -> t -> int end
module type S = sig type elt type t val init : elt list -> t val find : elt -> t -> elt val union : elt -> elt -> t -> unit end
module Make ( X : HashedOrderedType ) = struct type elt = X . t module H = Hashtbl . Make ( X ) type cell = { mutable c : int ; data : elt ; mutable father : cell } type t = cell H . t let init l = let h = H . create 997 in List . iter ( fun x -> let rec cell = { c = 0 ; data = x ; father = cell } in l ; h let rec find_aux cell = if cell . father == cell then cell else let r = find_aux cell . father in cell . father <- r ; r let find x h = ( find_aux ( H . find h x ) ) . data let union x y h = let rx = find_aux ( H . find h x ) in let ry = find_aux ( H . find h y ) in if rx != ry then begin if rx . c > ry . c then ry . father <- rx else if rx . c < ry . c then rx . father <- ry else begin rx . c <- rx . c + 1 ; ry . father <- rx end end end
let test_check_union context = let assert_type_errors = assert_type_errors ~ context in assert_type_errors { | from typing import Union class A : attr : bool = True class B : attr : str = " q " def foo ( y : Union [ A , B ] ) -> None : y . attr = False } | [ " Incompatible attribute type [ 8 ] : Attribute ` attr ` declared in class ` B ` has type ` str ` but \ is used as type ` bool ` . " ; ] ; assert_type_errors { | from typing import Union class A : attr : bool = True class B : attr : str = " q " def foo ( y : Union [ A , B ] ) -> None : y . attr = 2 } | [ " Incompatible attribute type [ 8 ] : Attribute ` attr ` declared in class ` A ` has type ` bool ` but \ is used as type ` int ` . " ; " Incompatible attribute type [ 8 ] : Attribute ` attr ` declared in class ` B ` has type ` str ` but \ is used as type ` int ` . " ; " Incompatible variable type [ 9 ] : y . attr is declared to have type ` Union [ bool , str ] ` but is \ used as type ` int ` . " ; ] ; assert_type_errors { | from typing import Union class A : attr1 : int = 2 class B : attr : str = " q " def foo ( y : Union [ A , B ] ) -> None : y . attr1 = 3 } | [ " Undefined attribute [ 16 ] : ` B ` has no attribute ` attr1 ` . " ] ; assert_type_errors { | from typing import Union class A : attr : Union [ bool , int ] = True class B : attr : Union [ str , int ] = " q " def foo ( y : Union [ A , B ] ) -> None : y . attr = 3 } | [ ] ; assert_type_errors { | import typing def foo ( ) -> typing . Union [ str , int ] : return 1 . 0 } | [ " Incompatible return type [ 7 ] : Expected ` Union [ int , str ] ` but got ` float ` . " ] ; assert_type_errors { | from builtins import condition import typing def foo ( ) -> typing . Union [ str , int ] : if condition ( ) : return 1 else : return ' foo ' } | [ ] ; assert_type_errors { | import typing def takes_int ( a : int ) -> None : . . . def takes_str ( a : str ) -> None : . . . def foo ( a : typing . Union [ str , int ] ) -> None : if isinstance ( a , str ) : takes_str ( a ) else : takes_int ( a ) } | [ ] ; assert_type_errors { | import typing def foo ( a : typing . Union [ str , int , float ] ) -> int : if isinstance ( a , int ) : return a else : return a } | [ " Incompatible return type [ 7 ] : Expected ` int ` but got ` Union [ float , str ] ` . " ] ; assert_type_errors { | import typing T = typing . TypeVar ( ' T ' , int , str ) def foo ( a : T ) -> float : return a } | [ " Incompatible return type [ 7 ] : Expected ` float ` but got ` Variable [ T <: [ int , str ] ] ` . " ] ; assert_type_errors { | import typing variable : typing . Union [ typing . Optional [ int ] , typing . Optional [ str ] ] = None def ret_opt_int ( ) -> typing . Optional [ int ] : return None variable = ret_opt_int ( ) } | [ ] ; assert_type_errors { | import typing def foo ( x : typing . Union [ int , Undefined ] ) -> None : pass foo ( 1 ) } | [ " Unbound name [ 10 ] : Name ` Undefined ` is used but not defined in the current scope . " ] ; assert_type_errors { | from builtins import Attributes , OtherAttributes import typing def foo ( x : typing . Union [ Attributes , OtherAttributes ] ) -> int : return x . int_attribute } | [ ] ; assert_type_errors { | from builtins import Attributes , OtherAttributes import typing def foo ( x : typing . Union [ Attributes , OtherAttributes ] ) -> int : return x . str_attribute } | [ " Incompatible return type [ 7 ] : Expected ` int ` but got ` unknown ` . " ; " Undefined attribute [ 16 ] : Item ` Attributes ` of ` typing . Union [ Attributes , OtherAttributes ] ` \ has no attribute ` str_attribute ` . " ; ] ; assert_type_errors { | from builtins import Attributes , OtherAttributes import typing def foo ( x : typing . Union [ OtherAttributes , Attributes ] ) -> int : return x . str_attribute } | [ " Incompatible return type [ 7 ] : Expected ` int ` but got ` unknown ` . " ; " Undefined attribute [ 16 ] : Item ` Attributes ` of ` typing . Union [ Attributes , OtherAttributes ] ` \ has no attribute ` str_attribute ` . " ; ] ; assert_type_errors { | import typing class Foo : def derp ( self ) -> int : . . . class Bar : def derp ( self ) -> int : . . . def baz ( x : typing . Union [ Foo , Bar ] ) -> int : return x . derp ( ) } | [ ] ; assert_type_errors { | import typing class Foo : def derp ( self ) -> int : . . . class Bar : def herp ( self ) -> int : . . . def baz ( x : typing . Union [ Foo , Bar ] ) -> int : return x . derp ( ) } | [ " Undefined attribute [ 16 ] : Item ` Bar ` of ` typing . Union [ Bar , Foo ] ` has no attribute ` derp ` . " ] ; assert_type_errors { | import typing class Equal : def __eq__ ( self , other : object ) -> typing . List [ int ] : . . . class GetItem : def __getitem__ ( self , x : int ) -> Equal : . . . class Contains : def __contains__ ( self , a : object ) -> bool : . . . def foo ( a : typing . Union [ GetItem , Contains ] ) -> None : 5 in a } | [ " Unsupported operand [ 58 ] : ` in ` is not supported for right operand type \ ` typing . Union [ Contains , GetItem ] ` . " ; ] ; assert_type_errors { | import typing def f ( x : typing . Optional [ typing . Union [ int , str ] ] ) -> None : return g ( x ) def g ( x : typing . Union [ typing . Optional [ int ] , typing . Optional [ str ] ] ) -> None : return f ( x ) } | [ ] ; assert_type_errors { | import typing def f ( x : typing . Union [ int , typing . Tuple [ int , int ] , typing . Optional [ str ] ] ) -> None : return g ( x ) def g ( x : typing . Optional [ typing . Union [ int , str , typing . Tuple [ int , int ] ] ] ) -> None : return f ( x ) } | [ ] ; assert_type_errors { | import typing def f ( x : typing . Union [ typing . Optional [ int ] , typing . Tuple [ int , int ] , typing . Optional [ str ] ] ) \ -> None : return g ( x ) def g ( x : typing . Optional [ typing . Union [ int , str , typing . Tuple [ int , int ] ] ] ) -> None : return f ( x ) } | [ ] ; assert_type_errors { | import typing def f ( x : typing . Union [ typing . Optional [ int ] ] ) -> None : return g ( x ) def g ( x : typing . Optional [ int ] ) -> None : return f ( x ) } | [ ] ; assert_type_errors { | import typing def f ( x : typing . Union [ int , str , None ] ) -> None : return g ( x ) def g ( x : typing . Optional [ typing . Union [ int , str ] ] ) -> None : return f ( x ) } | [ ] ; assert_type_errors { | import typing def f ( x : typing . Union [ int , typing . Union [ str , typing . Optional [ typing . Tuple [ int , int ] ] ] ] ) -> \ None : return g ( x ) def g ( x : typing . Optional [ typing . Union [ int , str , typing . Tuple [ int , int ] ] ] ) -> None : return f ( x ) } | [ ] ; assert_type_errors { | import typing def f ( x : typing . Union [ int , typing . Optional [ str ] ] ) -> None : return g ( x ) def g ( x : typing . Union [ str , typing . Optional [ int ] ] ) -> None : return f ( x ) } | [ ] ; assert_type_errors { | import typing def f ( x : typing . Union [ int , str , typing . Tuple [ int , int ] ] ) -> None : pass x : typing . Union [ int , typing . Optional [ str ] ] = . . . f ( x ) } | [ " Incompatible parameter type [ 6 ] : In call ` f ` , for 1st positional only parameter expected \ ` Union [ Tuple [ int , int ] , int , str ] ` but got ` Union [ None , int , str ] ` . " ; ] ; assert_type_errors { | import typing class A : def __call__ ( self , x : int ) -> bool : return True class B : def __call__ ( self , x : int ) -> str : return " True " def f ( x : typing . Union [ A , B ] ) -> None : return x ( 8 ) } | [ " Incompatible return type [ 7 ] : Expected ` None ` but got ` Union [ bool , str ] ` . " ] ; ( )
let ( ) = " union " >::: [ " check_union " >:: test_check_union ] |> Test . run
type enum_int = | Enum_int_0 | Enum_int_1 | Enum_int_other of int
let rec enum_int_of_js : Ojs . t -> enum_int = fun ( x3 : Ojs . t ) t -> let x4 = x3 in match Ojs . int_of_js x4 with | 0 -> Enum_int_0 | 1 -> Enum_int_1 | x5 -> Enum_int_other x5 fun ( x1 : enum_int ) enum_int -> match x1 with | Enum_int_0 -> Ojs . int_to_js 0 | Enum_int_1 -> Ojs . int_to_js 1 | Enum_int_other x2 -> Ojs . int_to_js x2
type enum_float = | Enum_float_0_1 | Enum_float_1_1 | Enum_float_other of float
let rec enum_float_of_js : Ojs . t -> enum_float = fun ( x8 : Ojs . t ) t -> let x9 = x8 in match Ojs . float_of_js x9 with | 0 . 1 -> Enum_float_0_1 | 1 . 1 -> Enum_float_1_1 | x10 -> Enum_float_other x10 fun ( x6 : enum_float ) enum_float -> match x6 with | Enum_float_0_1 -> Ojs . float_to_js 0 . 1 | Enum_float_1_1 -> Ojs . float_to_js 1 . 1 | Enum_float_other x7 -> Ojs . float_to_js x7
type enum_number_1 = | Enum_number_0 | Enum_number_1 | Enum_number_0_1 | Enum_number_1_1 | Enum_number_other of int
let rec enum_number_1_of_js : Ojs . t -> enum_number_1 = fun ( x13 : Ojs . t ) t -> let x14 = x13 in match Ojs . float_of_js x14 with | 0 . 1 -> Enum_number_0_1 | 1 . 1 -> Enum_number_1_1 | _ -> ( match Ojs . int_of_js x14 with | 0 -> Enum_number_0 | 1 -> Enum_number_1 | x15 -> Enum_number_other x15 ) x15 fun ( x11 : enum_number_1 ) enum_number_1 -> match x11 with | Enum_number_0 -> Ojs . int_to_js 0 | Enum_number_1 -> Ojs . int_to_js 1 | Enum_number_0_1 -> Ojs . float_to_js 0 . 1 | Enum_number_1_1 -> Ojs . float_to_js 1 . 1 | Enum_number_other x12 -> Ojs . int_to_js x12
type enum_number_2 = | Enum_number_0 | Enum_number_1 | Enum_number_0_1 | Enum_number_1_1 | Enum_number_other of float
let rec enum_number_2_of_js : Ojs . t -> enum_number_2 = fun ( x18 : Ojs . t ) t -> let x19 = x18 in match Ojs . float_of_js x19 with | 0 . 1 -> Enum_number_0_1 | 1 . 1 -> Enum_number_1_1 | x20 -> ( match Ojs . int_of_js x19 with | 0 -> Enum_number_0 | 1 -> Enum_number_1 | _ -> Enum_number_other x20 ) x20 fun ( x16 : enum_number_2 ) enum_number_2 -> match x16 with | Enum_number_0 -> Ojs . int_to_js 0 | Enum_number_1 -> Ojs . int_to_js 1 | Enum_number_0_1 -> Ojs . float_to_js 0 . 1 | Enum_number_1_1 -> Ojs . float_to_js 1 . 1 | Enum_number_other x17 -> Ojs . float_to_js x17
type enum_string = | Enum_string_foo | Enum_string_bar | Enum_string_other of string
let rec enum_string_of_js : Ojs . t -> enum_string = fun ( x23 : Ojs . t ) t -> let x24 = x23 in match Ojs . string_of_js x24 with | " foo " -> Enum_string_foo | " bar " -> Enum_string_bar | x25 -> Enum_string_other x25 fun ( x21 : enum_string ) enum_string -> match x21 with | Enum_string_foo -> Ojs . string_to_js " foo " | Enum_string_bar -> Ojs . string_to_js " bar " | Enum_string_other x22 -> Ojs . string_to_js x22
type enum_bool = | Enum_bool_true | Enum_bool_false
let rec enum_bool_of_js : Ojs . t -> enum_bool = fun ( x27 : Ojs . t ) t -> let x28 = x27 in match Ojs . bool_of_js x28 with | true -> Enum_bool_true | false -> Enum_bool_false fun ( x26 : enum_bool ) enum_bool -> match x26 with | Enum_bool_true -> Ojs . bool_to_js true | Enum_bool_false -> Ojs . bool_to_js false
type enum_bool_partial = | Enum_bool_true
let rec enum_bool_partial_of_js : Ojs . t -> enum_bool_partial = fun ( x30 : Ojs . t ) t -> let x31 = x30 in match Ojs . bool_of_js x31 with | true -> Enum_bool_true | _ -> assert false fun ( x29 : enum_bool_partial ) enum_bool_partial -> match x29 with | Enum_bool_true -> Ojs . bool_to_js true
type enum_bool_partial2 = | Enum_bool_true | Enum_bool_other of bool
let rec enum_bool_partial2_of_js : Ojs . t -> enum_bool_partial2 = fun ( x34 : Ojs . t ) t -> let x35 = x34 in match Ojs . bool_of_js x35 with | true -> Enum_bool_true | x36 -> Enum_bool_other x36 fun ( x32 : enum_bool_partial2 ) enum_bool_partial2 -> match x32 with | Enum_bool_true -> Ojs . bool_to_js true | Enum_bool_other x33 -> Ojs . bool_to_js x33