Created
May 26, 2021 18:55
-
-
Save saolof/338917b18a4d8edaa0b9b7a8fd1b7e9b to your computer and use it in GitHub Desktop.
Lexical lifetimes in Julia (simplified prototype)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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