Skip to content

Instantly share code, notes, and snippets.

@saolof
Created May 26, 2021 18:55
Show Gist options
  • Save saolof/338917b18a4d8edaa0b9b7a8fd1b7e9b to your computer and use it in GitHub Desktop.
Save saolof/338917b18a4d8edaa0b9b7a8fd1b7e9b to your computer and use it in GitHub Desktop.
Lexical lifetimes in Julia (simplified prototype)
abstract type GlobalScope end
abstract type _LifeTime{S<:GlobalScope} end
const LifeTime{S<:GlobalScope} = _LifeTime{>:S}
struct LivesExactly{L<:LifeTime,T}
val::T
LivesExactly(lt::Type{L},val::T) where {T,L<:LifeTime} = new{L,T}(val)
end
const LivesAtLeast{L,T} = LivesExactly{<:L,T}
# Example in use:
# Examples of lifetimes generated by scope macro.
abstract type Scope1 <: GlobalScope end
abstract type Scope2 <: Scope1 end
abstract type Scope3 <: GlobalScope end
# Simplified version of what would be generated by the @! function macro
function foo(context_lifetime::Type{L} ,x::LivesAtLeast{L,Int}) where {L<:LifeTime}
x.val
end
g = LivesExactly(LifeTime{GlobalScope}, 10)
a = LivesExactly(LifeTime{Scope1}, 10)
b = LivesExactly(LifeTime{Scope2}, 10)
c = LivesExactly(LifeTime{Scope3}, 10)
# Example of context-aware function calls with @!
foo(LifeTime{Scope1},a) # Works (exactly correct lifetime)
foo(LifeTime{Scope1},g) # Works (g outlives the context of the call)
foo(LifeTime{Scope1},b) # MethodError (possible use after free on b)
foo(LifeTime{Scope1},c) # MethodError (unrelated lifetimes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment