newsfilter.io
Tutorial

Understanding OCaml Locals as a Mode (with Sub-Moding) | OCaml Unboxed

  • Local and global are "modes" in OCaml, functioning similarly to types but governing memory lifetime and escape properties rather than value structure.
  • Every expression and variable is assigned a mode; variables must hold a mode derived from the expression they store after evaluation.
  • "Local" indicates an expression that cannot escape its declaration region, while "global" indicates an expression that is permitted to escape.
  • Explicit "local" annotations (e.g., local x) force a variable into local mode, whereas no explicit annotation exists to force global mode directly on a variable declaration.
  • Global mode can be inferred by passing a value to a function that accepts a global argument, such as mark_global, which acts as a filter for mode inference.
  • A critical safety constraint prevents assigning a local value to a global variable (e.g., let y = x where y is global and x is local) to ensure local values do not inadvertently escape their scope.
  • A sub-mode relationship exists where global < local, meaning any global expression can be treated as local, but a local expression cannot be treated as global.
  • The sub-mode logic implies that global values possess the "capability" to escape; placing them in a local context simply discards that capability, which is safe.
  • Conversely, converting a local value to global would invent the "escape capability" a value does not possess, which is forbidden by the type system.
  • Mode annotations on function parameters serve as a promise about the function's implementation rather than a strict requirement on the argument's usage site.
  • Marking a parameter as local ensures the implementation does not store the argument in a reference, preventing the argument from escaping the function.
  • Due to the sub-mode relationship, a function accepting a local parameter can safely receive either a local or a global argument.
  • There are four distinct function arrow types based on mode combinations for argument and result:
    • string -> string (global to global)
    • local string -> string (local to global)
    • string -> local string (global to local)
    • local string -> local string (local to local)
  • These four arrow types are fundamentally incompatible with each other and lack subtyping relationships, unlike standard type subtyping.
  • Storing different function types in a shared reference (e.g., ref (string -> string)) will result in errors if the specific arrow mode does not match the stored function's mode.
  • The local keyword applies to the function arrow itself, not the type it modifies; therefore, "local string" is invalid syntax, whereas "string local string" defines the arrow's mode.
  • The presenter notes that future videos will cover locality inference, which automatically applies local annotations to parameters to prevent escaping.