ffi/internal/Bindings.protos

Repository
guillermomolina/protos
Commit
379c6fa63685c39a5954cfbd577bfda3b4df8e75
Tree
8cd4f4afe29ae4c3866381f38c1858108e9799f6
Blob
f04b0cf7fa01bf33a2c3e9ba5b49e69876318ad4
Source
View exact source on GitHub
// THE LICENSED WORK IS PROVIDED UNDER THE TERMS OF THE ADAPTIVE PUBLIC LICENSE
// ("LICENSE") AS FIRST COMPLETED BY: Guillermo Adrián Molina. ANY USE, PUBLIC
// DISPLAY, PUBLIC PERFORMANCE, REPRODUCTION OR DISTRIBUTION OF, OR PREPARATION OF
// DERIVATIVE WORKS BASED ON, THE LICENSED WORK CONSTITUTES RECIPIENT'S ACCEPTANCE
// OF THIS LICENSE AND ITS TERMS, WHETHER OR NOT SUCH RECIPIENT READS THE TERMS OF
// THE LICENSE. "LICENSED WORK" AND "RECIPIENT" ARE DEFINED IN THE LICENSE. A COPY
// OF THE LICENSE IS LOCATED IN THE TEXT FILE ENTITLED "LICENSE.TXT" ACCOMPANYING
// THE CONTENTS OF THIS FILE. IF A COPY OF THE LICENSE DOES NOT ACCOMPANY THIS
// FILE, A COPY OF THE LICENSE MAY ALSO BE OBTAINED AT THE FOLLOWING WEB SITE:
// https://github.com/guillermomolina/protos
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
// the specific language governing rights and limitations under the License.

//! Private FFI bindings operations. Dependencies remain initializer-owned.

create: (Arrays, Interop, fail, isGroup, isOutTarget, isParameterDeclaration, isReturnDeclaration, make, metadata, nativeType, operation, owners, pointerType, providerContext, register, requireArity, requireString, voidDescriptor, getNativeContext) => {
    opaque: null
    nullable: null
    owned: null
    out: null
    publish: null
    declareBinding: null
    bind: null
    bindPreserving: null
    releaseOwned: null
    release: null
    addressOf: null

    methods: {
        opaque: (library, nativeTypeName, ...extra) => {
            (extra.size() == 0).ifFalse(() => fail())
            requireString(nativeTypeName)
            native: operation(library, "opaque", nativeTypeName)
            make("opaque", library, native, null)
        }

        nullable: (opaqueDescriptor, ...extra) => {
            (extra.size() == 0).ifFalse(() => fail())
            record: metadata(opaqueDescriptor)
            result: null
            if(record.layoutKind == "pointer") {
                // Nullability restricts later value admission; storage is unchanged.
                result = register("nullablePointer", "nullablePointer", record.size, record.align, null, null,
                    opaqueDescriptor, record.parts)
            } else {
                (record.kind == "opaque").ifFalse(() => fail())
                native: operation(record.library, "nullable", record.native)
                result = make("nullable", record.library, native, opaqueDescriptor)
            }
            result
        }

        owned: (opaqueDescriptor, releaseSymbol, releaseReturnDescriptor, ...extra) => {
            (extra.size() == 0).ifFalse(() => fail())
            record: metadata(opaqueDescriptor)
            returns: metadata(releaseReturnDescriptor)
            (record.kind == "opaque").ifFalse(() => fail())
            ((returns.kind == "void") || (returns.kind == "i32")).ifFalse(() => fail())
            requireString(releaseSymbol)
            native: operation(record.library, "owned", record.native, releaseSymbol,
                nativeType(record.library, releaseReturnDescriptor))
            make("owned", record.library, native, opaqueDescriptor)
        }

        out: (descriptor, ...extra) => {
            (extra.size() == 0).ifFalse(() => fail())
            record: metadata(descriptor)
            isOutTarget(record).ifFalse(() => fail())
            make("out", null, null, descriptor)
        }

        // Dispatch metadata only. Provider custody predates publication, including
        // results never published because a later native-result conversion fails.
        // An owned C handle is released through its library's destructor; a group
        // result is an allocation root released by the session context, exactly as
        // one answered by FFI.allocate, and never by a C destructor.
        publish: (library, descriptor, value) => {
            record: metadata(descriptor)
            if((record.kind == "owned") && (value !== null)) {
                owners[value] = library
            }
            if(isGroup(record)) {
                owners[value] = getNativeContext()
            }
            value
        }

        // Shared by bind and bindPreserving: one declaration path, one Closure shape.
        declareBinding: (library, symbol, returnDescriptor, argumentDescriptors, preserving) => {
            requireString(symbol)
            Array.recognizes(argumentDescriptors).ifFalse(() => fail())
            parameters: Array(...argumentDescriptors)
            isReturnDeclaration(metadata(returnDescriptor)).ifFalse(() => fail())
            // Validate the entire public declaration before composing provider values.
            // The result positions are the native return followed by every out.
            positions: 1
            for(parameter in parameters) {
                record: metadata(parameter)
                isParameterDeclaration(record).ifFalse(() => fail())
                if(record.kind == "out") { positions = positions + 1 }
            }
            signature: operation(library, "signature", nativeType(library, returnDescriptor))
            // Filled in place, then cut to the exact length: linear in the parameters.
            staged: Array(returnDescriptor, ...parameters)
            position: 1
            for(parameter in parameters) {
                signature = operation(library, "param", signature, nativeType(library, parameter))
                record: metadata(parameter)
                if(record.kind == "out") {
                    staged[position] = record.target
                    position = position + 1
                }
            }
            outputs: Arrays.take(staged, positions)
            if(preserving) {
                signature = operation(library, "preserving", signature)
            }
            parameters.freeze()
            outputs.freeze()
            binding: operation(library, "bind", symbol, signature)
            (...arguments) => {
                // Forward the exact vector; I085 admission owns arity, scalar ranges,
                // resource type/session/generation/liveness and UTF-8 checks.
                result: Interop.invoke(binding, ...arguments)
                answer: null
                if(positions == 1) {
                    answer = publish(library, returnDescriptor, result)
                }
                if(positions > 1) {
                    answer = Array(...outputs)
                    index: 0
                    for(descriptor in outputs) {
                        answer[index] = publish(library, descriptor, result[index])
                        index = index + 1
                    }
                }
                answer
            }
        }

        bind: (library, symbol, returnDescriptor, argumentDescriptors, ...extra) => {
            requireArity(extra)
            declareBinding(library, symbol, returnDescriptor, argumentDescriptors, false)
        }

        bindPreserving: (library: fail(), symbol: fail(), returnDescriptor: fail(),
                argumentDescriptors: fail(), ...extra) => {
            requireArity(extra)
            declareBinding(library, symbol, returnDescriptor, argumentDescriptors, true)
        }

        // Shared by release and the temporary roots of writeFields: one custody path.
        releaseOwned: (ownedHandle) => {
            owners.containsKey(ownedHandle).ifFalse(() => fail())
            library: owners.at(ownedHandle)
            owners.remove(ownedHandle)
            operation(library, "release", ownedHandle)
        }

        release: (ownedHandle, ...extra) => {
            (extra.size() == 0).ifFalse(() => fail())
            releaseOwned(ownedHandle)
        }

        addressOf: (value: fail(), ...extra) => {
            requireArity(extra)
            result: null
            libraryOwned: false
            if(owners.containsKey(value)) {
                owner: owners.at(value)
                if((owner === getNativeContext()) == false) {
                    result = operation(owner, "addressOf", value, pointerType(owner, voidDescriptor))
                    libraryOwned = true
                }
            }
            if(libraryOwned == false) {
                native: providerContext()
                result = operation(native, "regionAddress", value, pointerType(native, voidDescriptor))
            }
            result
        }
    }

    // Bind private operations once; factory-created closures use normal completion.
    opaque = methods.opaque
    nullable = methods.nullable
    owned = methods.owned
    out = methods.out
    publish = methods.publish
    declareBinding = methods.declareBinding
    bind = methods.bind
    bindPreserving = methods.bindPreserving
    releaseOwned = methods.releaseOwned
    release = methods.release
    addressOf = methods.addressOf

    {
        opaque: opaque
        nullable: nullable
        owned: owned
        out: out
        publish: publish
        declareBinding: declareBinding
        bind: bind
        bindPreserving: bindPreserving
        releaseOwned: releaseOwned
        release: release
        addressOf: addressOf
    }
}