Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rough-and-ready context lifetime management. #32

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions Sources/LLVM/BasicBlock.swift
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import llvmc

/// A basic block in LLVM IR.
public struct BasicBlock: Hashable {
public struct BasicBlock: Hashable, Contextual {

/// A handle to the LLVM object wrapped by this instance.
public let llvm: LLVMBasicBlockRef

public let context: ContextHandle

/// Creates an instance wrapping `llvm`.
internal init(_ llvm: LLVMBasicBlockRef) {
internal init(_ llvm: LLVMBasicBlockRef, in context: ContextHandle) {
self.llvm = llvm
self.context = context
}

}
Expand Down
48 changes: 48 additions & 0 deletions Sources/LLVM/Context.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import llvmc

/// Lifetime manager for a raw LLVM context.
public final class ContextHandle {

/// The raw LLVM context managed by `self`.
let raw: LLVMContextRef

/// An instance managing c.
init(_ c: LLVMContextRef) {
self.raw = c
}

deinit {
LLVMContextDispose(raw)
}

}

/// A context handle is valueless; all such handles are considered to be equal.
extension ContextHandle: Hashable {

public static func == (_: ContextHandle, _: ContextHandle) -> Bool { true }

public func hash(into hasher: inout Hasher) {}

}

/// A type whose operations require a particular live LLVMContextRef for validity.
public protocol Contextual {

/// A handle managing the LLVMContextRef that must remain live for operations on `self` to be
/// valid.
var context: ContextHandle { get }

}

extension Contextual {

/// Invokes `body`, returning its result, with the guarantee that `context` will remain live
/// during the execution of `body`.
func inContext<R>(body: () throws -> R) rethrows -> R {
try withExtendedLifetime(context) {
try body()
}
}

}
Loading
Loading