Commits

camlspotter committed 3892499

name space hack

  • Participants
  • Parent commits a85f7d6

Comments (0)

Files changed (4)

   test.ml is for an example.
 
   - api.ml provides the main Python/OCaml interface. 
-    Use "open Opycaml.Api" in your OCaml programs.
+    Use "open Opycaml.Api" in your OCaml programs. 
+    Once opened, Python/ML API functions are available by
+    Py.<Class>.<function> names. For example,
+
+       Py.Object.repr    for   PyObject_Repr
+       Py.String.check   for   PyStrnig_Check 
+
+    You can omit Py. prefix for the module names which do not collide
+    with OCaml standard library name space:
+
+       Object.repr       for   PyObject_Repr
+       (String is in OCaml standard library, so no short cut is available.)
 
   - Do not forget calling Base.initialize for initialization.
 
   - api.ml extends autoapi.ml, providing things not easily done by
     CamlIDL's code generator.
 
-  - A C function Py<Hoo>_<Bar> is found as a function <bar> 
-    (note thta the first letter is lowercased) in ML submodule <Hoo>. 
+  - A C function Py<Hoo>_<Bar> is mapped into an ML function Hoo.bar, 
+    where the first letter of "Bar" is lowercased.
+    
     For example:
-
-      PyString_Check => String.check
       PyObject_Repr =>  Object.repr
+      PyString_Check => String.check   
+               ( Note that String module is available by Py.String )
 
     There is one exception: If a C function has all-capital-or-underscore
     postfix name, such as PyTuple_GET_ITEM, its ML function name is not
 
 open Autoapi
 
-module String = String
+module Py = struct
+  module String = String
+  module ByteArray = ByteArray
+  module Number = Number
+  module Type = Type
+  module Mapping = Mapping
+  module Dict = Dict
+  module DictProxy = DictProxy
+  module Module = Module
+  module Index = Index
+  module Import = Import
+  module Iter = Iter
+  module Callable = Callable
+  module Sequence = Sequence
+  module Eval = Eval
+  module Run = Run
+  
+  module Tuple : sig
+    include module type of Tuple
+  
+    val from_list : [> _Object] t list -> _Tuple t
+    val to_list : _Tuple t -> _Object t list
+  end = struct
+    include Tuple
+  
+    let from_list lst =
+      let tpl = new_ (List.length lst) in
+      Utils.List.iteri (setItem tpl) lst;
+      tpl
+  
+    let to_list a =
+      let len = _GET_SIZE a in
+      let rec f st = function
+        | -1 -> st
+        | n -> f (getItem a n :: st) (n-1)
+      in
+      f [](len-1)
+  end
+  
+  module Cback : sig
+    val functions : (string, _Object t option -> _Object t list -> _Object t) Hashtbl.t
+    val initialize : unit -> unit
+  end = struct
+    (** Python calls OCaml function *)
+    open Type
+    
+    let functions = Hashtbl.create 107
+    
+    type result = 
+      | Ok of _Object t
+      | Error of string
+      | Not_found of _Object t
+    
+    let callback : _Object t option -> _Tuple t -> result = fun self_option args_tuple ->
+      let args = Tuple.to_list args_tuple in
+      match args with
+      | [] -> assert false
+      | name_object::args ->
+  	let f = try Some (Hashtbl.find functions (String.asString (Object.str name_object))) with _ -> None in
+  	match f with
+  	| None -> Not_found name_object
+  	| Some f -> try Ok (f self_option args) with e -> Error (Printexc.to_string e)
+    ;;
+  
+    let initialize () = Callback.register "( ゚∀゚)o彡°O'PyCaml callback" callback
+  end
+  
+  module Base : sig
+    include module type of Base
+  
+    external none : unit -> _None t = "opycaml_none"
+      (** Get Py_None object. *)
+  
+    external phys_eq : [>_Object] t -> [>_Object] t -> bool = "opycaml_physical_equal"
+      (** Checks physical equality of objects *)
+  
+    (* reference count functions: use with care *)
+    external refcnt : [>_Object] t -> int = "opycaml_refcnt"
+    external incref : [>_Object] t -> unit = "opycaml_incref"
+    external decref : [>_Object] t -> unit = "opycaml_decref"
+  
+    (* get address of objects for debugging *)
+    external address : [>_Object] t -> nativeint = "opycaml_address"
+  
+    val initialize : unit -> unit
+      (** Python api initialization with OCaml exception registeration.
+  	Any other function in OPyCaml must be called after [initialize ()].
+      *)
+  
+    val debug : string -> [>_Object] t -> unit
+      (** debug print of objects *) 
+  
+    val main : string list -> int
+      (** Call to Py_Main
+  
+  	The main program for the standard interpreter. This is made available for programs which embed Python. The argc and argv parameters should be prepared exactly as those which are passed to a C program’s main() function. It is important to note that the argument list may be modified (but the contents of the strings pointed to by the argument list are not). The return value will be the integer passed to the sys.exit() function, 1 if the interpreter exits due to an exception, or 2 if the parameter list does not represent a valid Python command line.
+  	Note that if an otherwise unhandled SystemError is raised,
+  	this function will not return 1, but exit the process, as long
+  	as Py_InspectFlag is not set.
+  
+  	Bug: Py_Main never returns to OCaml at exit(_), while CTRL+D works fine.
+      **)
+  end = struct
+    include Base
+  
+    external none : unit -> _None t = "opycaml_none"
+    external poly_none : unit -> 'a t = "opycaml_none" (* unsafe *)
+    external phys_eq : [>_Object] t -> [>_Object] t -> bool = "opycaml_physical_equal"
+    external refcnt : [>_Object] t -> int = "opycaml_refcnt"
+    external incref : [>_Object] t -> unit = "opycaml_incref"
+    external decref : [>_Object] t -> unit = "opycaml_decref"
+    external address : [>_Object] t -> nativeint = "opycaml_address"
+  
+    external internal_init : unit -> unit = "opycaml_init"
+    let initialize () =
+      Callback.register_exception "( ゚∀゚)o彡°O'PyCaml exception" (Error (poly_none (), poly_none ()));
+      Cback.initialize ();
+      internal_init ();
+      _internal_initialize ()
+  
+    let debug name o =
+      let cnt = refcnt o in
+      let repr = String.asString (Object.repr o) in
+      let address = address o in
+      Printf.eprintf "%s : %d : %nx : %s\n%!" name cnt address repr
+  
+    external _main : int -> string list -> int = "opycaml_Py_Main"
+    let main argv = _main (List.length argv) argv
+  end
+  
+  module Object = struct
+    include Object
+  
+    let call callable ?kwd list =
+      _internal_call callable (Tuple.from_list list) kwd
+  
+    let callObject callable = function
+      | [] -> _internal_callObject callable None
+      | list -> _internal_callObject callable (Some (Tuple.from_list list))
+  end
+  
+  module Err : sig
+    include module type of Err
+  
+    external reraise : unit -> 'a = "opycaml_error"
+      (** reraise the current exception. 
+  	Err.Occured() must be return Some. Otherwise Failwith is
+      raised instead. *)
+  
+    val normalizeException : unit -> (_Object t * _Object t * _Object t) option
+  end = struct
+    include Err
+      
+    external reraise : unit -> 'a = "opycaml_error"
+  
+    let normalizeException () =
+      match occurred () with
+      | None -> None
+      | Some _ -> Some (_internal_normalizeException ())
+  end
+  
+  module Int : sig
+    include module type of Int
+  
+    val asLong : [>_Int] t -> int
+      (** raises Error at overflow *)
+  end = struct
+    include Int
+  
+    let asLong t =
+      let res = _internal_asLong t in
+      if res <> -1 then res
+      else match Err.occurred () with
+      | None -> -1
+      | Some _ -> Err.reraise ()
+  end
+end
+  
+(* Name space hack: Modules whose names do not collide with the OCaml
+   standard library are exported here too. *)
+open Py
+(* module String = String -- collides with OCaml standard library *)
 module ByteArray = ByteArray
 module Number = Number
 module Type = Type
 module Sequence = Sequence
 module Eval = Eval
 module Run = Run
-
-module Tuple : sig
-  include module type of Tuple
-
-  val from_list : [> _Object] t list -> _Tuple t
-  val to_list : _Tuple t -> _Object t list
-end = struct
-  include Tuple
-
-  let from_list lst =
-    let tpl = new_ (List.length lst) in
-    Utils.List.iteri (setItem tpl) lst;
-    tpl
-
-  let to_list a =
-    let len = _GET_SIZE a in
-    let rec f st = function
-      | -1 -> st
-      | n -> f (getItem a n :: st) (n-1)
-    in
-    f [](len-1)
-end
-
-module Cback : sig
-  val functions : (string, _Object t option -> _Object t list -> _Object t) Hashtbl.t
-  val initialize : unit -> unit
-end = struct
-  (** Python calls OCaml function *)
-  open Type
-  
-  let functions = Hashtbl.create 107
-  
-  type result = 
-    | Ok of _Object t
-    | Error of string
-    | Not_found of _Object t
-  
-  let callback : _Object t option -> _Tuple t -> result = fun self_option args_tuple ->
-    let args = Tuple.to_list args_tuple in
-    match args with
-    | [] -> assert false
-    | name_object::args ->
-	let f = try Some (Hashtbl.find functions (String.asString (Object.str name_object))) with _ -> None in
-	match f with
-	| None -> Not_found name_object
-	| Some f -> try Ok (f self_option args) with e -> Error (Printexc.to_string e)
-  ;;
-
-  let initialize () = Callback.register "( ゚∀゚)o彡°O'PyCaml callback" callback
-end
-
-module Base : sig
-  include module type of Base
-
-  external none : unit -> _None t = "opycaml_none"
-    (** Get Py_None object. *)
-
-  external phys_eq : [>_Object] t -> [>_Object] t -> bool = "opycaml_physical_equal"
-    (** Checks physical equality of objects *)
-
-  (* reference count functions: use with care *)
-  external refcnt : [>_Object] t -> int = "opycaml_refcnt"
-  external incref : [>_Object] t -> unit = "opycaml_incref"
-  external decref : [>_Object] t -> unit = "opycaml_decref"
-
-  (* get address of objects for debugging *)
-  external address : [>_Object] t -> nativeint = "opycaml_address"
-
-  val initialize : unit -> unit
-    (** Python api initialization with OCaml exception registeration.
-	Any other function in OPyCaml must be called after [initialize ()].
-    *)
-
-  val debug : string -> [>_Object] t -> unit
-    (** debug print of objects *) 
-
-  val main : string list -> int
-    (** Call to Py_Main
-
-	The main program for the standard interpreter. This is made available for programs which embed Python. The argc and argv parameters should be prepared exactly as those which are passed to a C program’s main() function. It is important to note that the argument list may be modified (but the contents of the strings pointed to by the argument list are not). The return value will be the integer passed to the sys.exit() function, 1 if the interpreter exits due to an exception, or 2 if the parameter list does not represent a valid Python command line.
-	Note that if an otherwise unhandled SystemError is raised,
-	this function will not return 1, but exit the process, as long
-	as Py_InspectFlag is not set.
-
-	Bug: Py_Main never returns to OCaml at exit(_), while CTRL+D works fine.
-    **)
-end = struct
-  include Base
-
-  external none : unit -> _None t = "opycaml_none"
-  external poly_none : unit -> 'a t = "opycaml_none" (* unsafe *)
-  external phys_eq : [>_Object] t -> [>_Object] t -> bool = "opycaml_physical_equal"
-  external refcnt : [>_Object] t -> int = "opycaml_refcnt"
-  external incref : [>_Object] t -> unit = "opycaml_incref"
-  external decref : [>_Object] t -> unit = "opycaml_decref"
-  external address : [>_Object] t -> nativeint = "opycaml_address"
-
-  external internal_init : unit -> unit = "opycaml_init"
-  let initialize () =
-    Callback.register_exception "( ゚∀゚)o彡°O'PyCaml exception" (Error (poly_none (), poly_none ()));
-    Cback.initialize ();
-    internal_init ();
-    _internal_initialize ()
-
-  let debug name o =
-    let cnt = refcnt o in
-    let repr = String.asString (Object.repr o) in
-    let address = address o in
-    Printf.eprintf "%s : %d : %nx : %s\n%!" name cnt address repr
-
-  external _main : int -> string list -> int = "opycaml_Py_Main"
-  let main argv = _main (List.length argv) argv
-end
-
-module Object = struct
-  include Object
-
-  let call callable ?kwd list =
-    _internal_call callable (Tuple.from_list list) kwd
-
-  let callObject callable = function
-    | [] -> _internal_callObject callable None
-    | list -> _internal_callObject callable (Some (Tuple.from_list list))
-end
-
-module Err : sig
-  include module type of Err
-
-  external reraise : unit -> 'a = "opycaml_error"
-    (** reraise the current exception. 
-	Err.Occured() must be return Some. Otherwise Failwith is
-    raised instead. *)
-
-  val normalizeException : unit -> (_Object t * _Object t * _Object t) option
-end = struct
-  include Err
-    
-  external reraise : unit -> 'a = "opycaml_error"
-
-  let normalizeException () =
-    match occurred () with
-    | None -> None
-    | Some _ -> Some (_internal_normalizeException ())
-end
-
-module Int : sig
-  include module type of Int
-
-  val asLong : [>_Int] t -> int
-    (** raises Error at overflow *)
-end = struct
-  include Int
-
-  let asLong t =
-    let res = _internal_asLong t in
-    if res <> -1 then res
-    else match Err.occurred () with
-    | None -> -1
-    | Some _ -> Err.reraise ()
-end
-
-
+module Tuple = Tuple
+module Cback = Cback
+module Base = Base
+module Object = Object
+module Err = Err
+module Int = Int

File example/test.ml

 
   let res = Object.callObject (Callable.coerce capitalize) [lowercase] in
 
-  prerr_endline (String.asString (String.coerce res));
+  prerr_endline (Py.String.asString (Py.String.coerce res));
 
   Base.finalize ()
 ;;
     ignore (Import.importModule "hogehoge")
   with
   | Error (e, detail) ->
-      Printf.eprintf "Error: %s %s\n%!" (String.asString (Object.repr e)) (String.asString (Object.repr detail))
+      Printf.eprintf "Error: %s %s\n%!" (Py.String.asString (Object.repr e)) (Py.String.asString (Object.repr detail))
 ;;
 
 let _ =
-  let o = String.fromString "hello world" in
+  let o = Py.String.fromString "hello world" in
   Base.debug "o" o;
 
   assert (Base.phys_eq o o);
     let res = Object.callObject (Callable.coerce capitalize) [o] in
     Printf.eprintf "res : refcnt = %d\n%!" (Base.refcnt res);
     prerr_endline "function called!";
-    prerr_endline (String.asString (String.coerce res));
-    prerr_endline (String.asString o);
+    prerr_endline (Py.String.asString (Py.String.coerce res));
+    prerr_endline (Py.String.asString o);
 
     let minus_1 = Int.fromLong (-1) in
     assert (Int.asLong minus_1 = -1); 
 
   with
   | Error (e, detail) -> 
-      Printf.eprintf "Error: %s %s\n%!" (String.asString (Object.repr e)) (String.asString (Object.repr detail))
+      Printf.eprintf "Error: %s %s\n%!" (Py.String.asString (Object.repr e)) (Py.String.asString (Object.repr detail))
 ;;
 
 let _ = Base.finalize ()