Skip to content
This repository
tag: v1903
Fetching contributors…

Cannot retrieve contributors at this time

file 361 lines (276 sloc) 13.029 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
(*
Copyright © 2011 MLstate

This file is part of OPA.

OPA is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.

OPA is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.

You should have received a copy of the GNU Affero General Public License
along with OPA. If not, see <http://www.gnu.org/licenses/>.
*)

(**
Runtime library for continuations and concurrency.

The role of this library is to provide the necessary primitives introduced by the Cps transformation,
to be used at runtime.

This library is meant to be used
- directly by low-level libraries (appserver, db3)
- transparently by the QML CPS-based compiler

Beware, by hacking this lib, you should update QmlCpsRewriter consistently

@author David Rajchenbach-Teller
@author Mathieu Barbin
*)

(**
{6 Continuations}
*)

type continuation_options =
    {
      movable : bool;
      (**[true] if the continuation may be stolen by another server,
[false] otherwise*)
      atomic : bool;
      (**[true] if the continuation should not be scheduled.
This can cause runtime errors if the continuation contains [wait].*)
      _lazy : bool;
      (**[true] if the continuation should be evaluated rather than scheduled.*)
    }

(**A mechanism for returning values of type ['a].
Optimized implementations should make this a [goto].*)
type 'a continuation

type 'a func0 = 'a continuation -> unit
(**The implementation of a function with type ['a -> 'b], after cps-transfo*)
type ('a, 'b) func = 'a -> 'b func0

(**The default options for continuations: movable.*)
val default_options : continuation_options

(** create a cont from its fields : not used currently by the generated code *)
val make_cont: continuation_options -> QmlClosureRuntime.t -> 'a continuation
val make_cont_ml: continuation_options -> ('a -> unit) -> 'a continuation

(** a short name because of the number of occurrences in the generated code *)
val cont: QmlClosureRuntime.t -> 'a continuation
val cont_ml: ('a -> unit) -> 'a continuation

(** creating a cont from an other cont, changing nothing but the payload
this function is used in the generated code to be able to pass the thread context *)
val ccont : 'b continuation -> QmlClosureRuntime.t -> 'a continuation
val ccont_ml : 'b continuation -> ('a -> unit) -> 'a continuation

(**Return a value using a continuation : apply the continuation to the value *)
val return : 'a continuation -> 'a -> unit

(** Like [return] but can't be schedule before return value to
continuation. *)
val execute : 'a continuation -> 'a -> unit

val update_cont : 'a continuation -> _ continuation option -> string -> string -> _ -> 'a continuation
val print_trace : 'a continuation -> unit

(** [push_cont k x] Like return but asynchronous. Create a task that
apply the continuation to the value, and push it to the cps
scheduler. *)
val push_cont : 'a continuation -> 'a -> unit

(** {6 thread context} *)

(**
Setting and accessing the \@thread_context from a continuation. If the thread_context has not been set with
[with_thread_context], the returned value is [None]. Otherwise, [thread_context] returns the
last context set by [with_thread_context].

Implementation uses type [Obj.t], which means that you should carrefully use the pair [thread_context/with_thread_context].
In practice, these two functions are not used directly, but are exported in the bsl with the tag [restricted:cps],
which means that they can be used only be code generated by [QmlCpsRewriter], from the 2 following directives (available
in opa and qml) :
+ \@thread_context
+ \@with_thread_context

@see "thread_context.opa" from the stdlib of opa to see how the final user can use this feature.
*)
(** *)
val thread_context : 'a continuation -> 'thread_context option
val with_thread_context : 'thread_context -> 'a continuation -> 'a continuation

(** Similar to thread_context, but for a specific purpose *)
val transaction_context : 'a continuation -> 'transaction_context option
val with_transaction_context : 'transaction_context -> 'a continuation -> 'a continuation

(** {6 exceptions} *)

(** Used to get the exception-handling continuation *)
val handler_cont: 'a continuation -> 'exc continuation

(** Catches exceptions thrown within the continuation *)
val catch : QmlClosureRuntime.t -> 'a continuation -> 'a continuation
val catch_ml : ('exc -> 'a continuation -> unit) -> 'a continuation -> 'a continuation

(** Stores and retrieves backtrace data on a cyclic queue. *)
val bt_add : string -> unit
val bt_take : unit -> string
(** Prints a function name and value of its arguments (treated by obj.magic) *)
(* TODO: due to limitation of libbsl, it's only the first argument for now *)
val fun_args2string : string -> 'a -> string
(* The argument is the first world displayed, e.g. "Raised" or "Interrupted" *)
val display_backtrace : string -> unit

(** FROM HERE, PRIMITIVES HAVE AN INTERACTION WITH THE SCHEDULER *)

(** {6 Call-cc : uncps} *)

val uncps : string -> 'a continuation -> QmlClosureRuntime.t -> 'b

val uncps_ml:
  string ->
  'a continuation ->
  ('b continuation -> unit) -> 'b

(**callcc_directive : the real version of call-cc (used in resolution of directive \@callcc) *)
val callcc_directive : (* (('a continuation, unit) func, 'a) func *)
  (* f : *) ( 'a continuation -> 'unit continuation -> unit ) ->
  'a continuation ->
  unit

(** Apply a function to an argument.

In concurrent implementations, this application can also
have an effect on scheduling and/or garbage-collection.

@TODO When a prototype is complete, add hand-optimized
[apply2], [apply3]...*)
val apply: ('a, 'b) func -> 'a -> 'b continuation -> unit
(*val apply: ('a, 'b) func -> 'b continuation -> 'a -> unit*)

(**
Instead of apply2, apply3, we use apply0 :

apply3 f x y z k ==> apply0 (fun () -> f x y z k) k

The ml closure is created anyway inside apply-n.
K is repassed because we need some other infos from it.
*)
val apply0: QmlClosureRuntime.t -> 'b continuation -> unit
val apply0_ml : (unit -> unit) -> 'b continuation -> unit

val set_nb_step_apply: int -> unit (* Set the number of apply for each scheduling step *)

(**
{6 Futures}
*)

(**
Future are used for evaluation in pseudo-concurrency.
*)

(**A value of type ['a], which may already have been computed
or may be computed as a background task.*)
type 'a future

val spawn: (unit -> 'a continuation -> unit) -> 'a future

val wait: 'a future -> 'a continuation -> unit

(** exported low-level barrier management for top level value *)

(**
Creating a new barrier.
ignored argument : because QmlServerLib.empty is not unit.
For optimization purpose, we does not want to project this bypass *)
val make_barrier : string -> 'a future

(** Print a barrier *)
val print_barrier : Format.formatter -> 'a future -> unit

(**
Releasing a barrier means provide its terminaison value.
+ <!> Barrier should be released only once, or it would cause
an internal error.
+ <!> Releasing a barrier leads to compute all pending continuation
related to this barrier. The function returns only when all pending
continuation have been computed. In practice, a pending continuation
of a barrier is a continuation which only {e push} a task using the
release value in the main queue, but does not do real computation.
*)
val release_barrier : 'a future -> 'a -> unit

(**
Check if a barrier has been released.
Used for rewritting the top-level.
The function returns [true] if the barrier is computed,
or if an exception occurred during the computation of the barrier.
*)
val is_released : _ future -> bool

(** Initialize some structure for a future use of [toplevel_wait]. *)
val before_wait : 'projection_friendly -> unit

(**
Check if the barrier was realeased and returns the computed value
else raise a [Failure].
This function is specially used only for toplevel rewritting.
*)
val toplevel_wait : 'a future -> 'a

(** {6 Magic} *)

(**
Because of ocaml generalization error on value restriction, we need to
deal with black_barrier to evoid the apparition of Obj.magic everywhere
using these [black_*] function is the default behavior of back-ends,
using MLSTATE_QMLC_NO_MAGIC (debug env toggle) will make the back-ends
not use them.

Essentially, these function are implemented with Obj.magic,
but the type transformation is more specific, to loose less type informations,
and potentially catch more errors.
*)

(** *)
val magic_cont : 'a continuation -> 'b continuation
val magic_func : ('a, 'b) func -> ('c, 'd) func
val magic_func0 : (_ func0) -> _ func0
val magic_func1 : (_ -> _ func0) -> (_ -> _ func0)
val magic_func2 : (_ -> _ -> _ func0) -> (_ -> _ -> _ func0)
val magic_func3 : (_ -> _ -> _ -> _ func0) -> (_ -> _ -> _ -> _ func0)
val magic_func4 : (_ -> _ -> _ -> _ -> _ func0) -> (_ -> _ -> _ -> _ -> _ func0)
val magic_func5 : (_ -> _ -> _ -> _ -> _ -> _ func0) -> (_ -> _ -> _ -> _ -> _ -> _ func0)
val magic_func_more : _ -> _

type black_future
val black_make_barrier : string -> black_future
val black_release_barrier : black_future -> 'a -> unit
val black_toplevel_wait : black_future -> 'a

(** {6 A few useful functions} *)

(** Open this module for duck-style cps-programming©. This is a variant from
libbase/Cps that assumes your continuations are QmlCps-continuations, not
functions.

See guidelines in libbase/Cps; as an exception, when we need conversion
between functions and continuations, we write: {[
f @> ccont_ml k
@> fun x -> x+1 |> k
]}
While this forces us to relax the type of [@>], it keeps the readability
and avoids added parentheses.
*)
module Ops : sig
  (** Duck operator: apply a cps-function to a continuation (['a] should normally
be a continuation and ['b] unit, but keeping it polymorph is easier when
dealing with continuations-as-functions *)
  val (@>) : ('a -> 'b) -> 'a -> 'b

  (** The pipe operator: pass a computed value to your continuation *)
  val (|>) : 'a -> 'a continuation -> unit
end

(** Just like List.fold_left, but in Cps. While coding a cps-fold based on
List.fold is a fun exercise, it's less efficient. *)
val fold_list : ('acc -> 'a -> 'acc continuation -> unit) -> 'acc -> 'a list -> 'acc continuation -> unit

(** Maps the given cps function on the elements of the list, in parallel *)
val map_list : ('a -> 'b continuation -> unit) -> 'a list -> 'b list continuation -> unit

(** Iters the given cps function on the elements of the list, in parallel *)
val iter_list : ('a -> unit continuation -> unit) -> 'a list -> unit continuation -> unit

val fold_array : ('acc -> 'a -> 'acc continuation -> unit) -> 'acc -> 'a array -> 'acc continuation -> unit

(*
(*
{6 Tasks}
*)

type task (*A very lightweight thread.*)
val task_of_fun: unit continuation -> task (*Create a new task.*)
val push: task -> unit (*Schedule a task for execution.*)

(*If a task is waiting to be executed, remove it from the queue
and return it.*)
val steal: unit -> task option

*)
(*
{6 Interaction with asynchronous I/O}

These functions provide support for interacting
with the asynchronous IO features provided
by most operating systems.
*)

(*
Prepare a callback for a function which may be called non-deterministically.

Use [callback_of_fun] whenever you intend to invoke
an asynchronous function that will only
inform the system of its termination by calling a callback.

For instance, assume the existence of a function
[async_read_contents: file -> (string -> unit)].
This function, provided by the Operating System,
opens a file for reading, reads in the background
and eventually sends the result of reading to some callback.
In order to ensure nice cooperation
with the scheduler, we wish this function
to be seen as [read_contents: file -> string future].

Calling [callback_of_fun f] produces a pair [(cb, future)],
where [cb] does the same computation
as [f] but the result may be consulted from [future].

To adapt [async_read_contents], we may just define [read_contents] as

{[
let read_contents file =
let (cb, future) = callback_of_fun (fun x -> x) in
callback_of_fun file cb;
future
]}
*)

(*
type ('a, 'b) pair = {f_0: 'a; f_1: 'b}(*TODO: Get rid of this?*)

val callback_of_fun: ('a -> 'b) -> (('a -> unit), 'b future) pair


(*
Simplified version of [callback_of_fun] for most common cases.

This is equivalent to [callback_of_fun (fun x -> x)], just slightly faster.
*)
val callback_post: unit -> (('a -> unit), 'a future) pair


*)
Something went wrong with that request. Please try again.