Joyeer Language Specification
Chapters
On this page (10 sections)

§19 C Interoperation

Specification status: this chapter defines the restricted C boundary in the broader language design. It does not introduce a public pointer or general-purpose unsafe system.

Implementation status: the authorized native implementation supports @c_extern, @c_export, and @c_data, bodyless imports, C-callable scalar exports, all §19.4 scalar mappings, restricted buffer imports (§19.4.3), bare byte pointers (§19.4.4), compiler intrinsics (§19.4.5), and core-unit rules (§19.4.7). The example in §19.2 requires an explicitly authorized compilation context; it is not an ordinary application program. Native platform acceptance is recorded in the C binding implementation. Section 19.10 defines the limits of the supported memory adapters.

19.1 Scope and authorization

@c_extern imports a native function; @c_export provides a C-callable definition written in Joyeer. Both select the configured target's ordinary C calling convention. There is no abi argument or selection of another calling convention.

Only compilation units explicitly selected by the toolchain for native bindings may declare or directly call these bindings, including runtime construction and optional native-backed source libraries. Authorization is an explicit compilation input, not a property inferred from a path, module name such as Foundation, visibility modifier, or annotation itself. It is not inherited by importing an authorized unit, nor automatically granted to that unit's dependencies. Ordinary code uses unannotated, checked Joyeer APIs instead. This restriction does not establish an OS sandbox or prove the safety of a native implementation.

The build interface that selects authorized units is an implementation contract; this chapter does not invent a command-line flag, manifest field, object-output mode, or separately linkable module facility.

19.2 Declarations and annotation arguments

@c_extern(symbol: "joyeer_native_identity")
func nativeIdentity(value: Int): Int

@c_export(symbol: "joyeer_rt_identity")
func runtimeIdentity(value: Int): Int {
    return nativeIdentity(value: value)
}
AnnotationDefinition providerFunction body
@c_externA native link inputMust be absent
@c_exportThe annotated Joyeer functionRequired

These annotations precede any visibility modifier on a top-level free function declaration (§3.2). They are not permitted on methods, initializers, accessors, types, fields, or bindings. A declaration may have exactly one C binding annotation: repeats and combining the two are errors.

Each annotation requires a first named argument, symbol:, whose value is a nonempty string literal. A @c_extern may then add pointer: arguments, each a string literal naming one of its [UInt8] parameters (§19.4.4). Expressions, inferred names, omitted arguments, duplicate symbol: arguments, and other arguments, including abi, library, or a repeated signature, are errors. The decoded symbol must be an ASCII C identifier: [A-Za-z_][A-Za-z0-9_]*. Embedded NUL, whitespace, and platform linker decorations are not allowed.

Parameter types and the result type must be explicit. A unit result may be written : Void or : (), but it may not be omitted on a C binding. Parameter names and labels follow §3.2.1. Scalar parameters use default or explicit borrowing; imports may also use the buffer access forms in §19.4.3. Defaults for argument values are not admitted. The function must satisfy the signature rules in §19.4 and §19.5.

A bodyless declaration is valid only with @c_extern; an empty {} is still a body and is invalid on an import. Ordinary functions and @c_export definitions require bodies. The declaration and attribute productions are consolidated in Appendix C.

19.3 Source calls and native symbols

The function declaration is the sole source signature. Joyeer calls use its source name, argument labels, access rules, and declaration order. Labels and internal parameter names are not part of the C ABI. A binding does not require a second user-maintained signature file.

symbol names the C linkage identifier, not a module-qualified Joyeer name or a raw object-file spelling. The backend applies the target's normal C symbol decoration. For example, a target's object-file underscore prefix is not included in symbol: "joyeer_rt_identity". No overload suffix or Joyeer-specific mangling is added to that C linkage name.

Joyeer visibility and C linkage are independent:

For every native symbol visible in a compilation, all declarations must agree on a normalized C ABI signature: calling convention, parameter count and order, parameter representations, and result representation. Source labels, internal names, and visibility do not affect this comparison. Repeated compatible imports are allowed; incompatible imports are errors. An import may refer to a compatible export, but there may be at most one definition of that symbol in the linked program. Two Joyeer exports with the same symbol are errors even if their signatures agree. Conflicts with definitions supplied by native objects must also fail, not select a provider silently.

Annotations do not change executable entry-point selection (§3.2.6). They are not permitted on the Joyeer executable entry, and a C export may not claim main or another entry symbol owned by the toolchain. Runtime object construction does not turn a missing application entry into a valid executable.

19.4 C scalar representations

The following are the complete by-value scalar representations for this revision. They apply equally to imports and exports. These are ABI representations, not new source aliases or promises about the ordinary Joyeer calling convention.

Joyeer typeC representationPermitted positions
Void / ()voidResult only
BoolC11 _Bool (bool from <stdbool.h>)Parameter and result
Int8int8_tParameter and result
UInt8uint8_tParameter and result
Int16int16_tParameter and result
UInt16uint16_tParameter and result
Int32int32_tParameter and result
UInt32uint32_tParameter and result
Int64, Intint64_tParameter and result
UInt64, UIntuint64_tParameter and result
FloatC float, IEEE 754 binary32Parameter and result
DoubleC double, IEEE 754 binary64Parameter and result

An empty Joyeer parameter list denotes a fixed, zero-argument C prototype, written (void) in C11. It is neither a Void parameter, an unspecified parameter list, nor a variadic function.

19.4.1 Target C data models

Bindings to C spelling rather than fixed-width typedefs must use the representation selected for the actual target, not the build host:

C type64-bit LP64 targets (Linux/macOS/iOS)64-bit LLP64 targets (Windows)
signed char / unsigned charInt8 / UInt8Int8 / UInt8
short / unsigned shortInt16 / UInt16Int16 / UInt16
int / unsigned intInt32 / UInt32Int32 / UInt32
long / unsigned longInt64 / UInt64Int32 / UInt32
long long / unsigned long longInt64 / UInt64Int64 / UInt64
size_tUInt64UInt64
ptrdiff_tInt64Int64

Int is always signed 64-bit, not C int or an address carrier (runtime units may use it as one; see the last rule of §19.5). UInt is always unsigned 64-bit, not a promise that every C unsigned type has that width. The table does not add support for a new target or data model.

Plain C char maps to Int8 when the target C implementation makes it signed, and to UInt8 when it makes it unsigned. Its signedness must be established for the configured target and native build options; it must not be inferred from the host or from the word char. Joyeer Char is a Unicode scalar and is never the representation of C char.

Windows BOOL is a signed 32-bit integer and uses Int32, not Bool. An explicit wrapper may interpret its zero/nonzero convention. A C typedef is admissible only when its underlying type has one of the specified scalar representations. Similar names or sizes do not establish compatibility for an enum, aggregate, or pointer.

This boundary does not add C-specific source aliases such as CInt, CLong, or CChar; those names are not reserved. A binding author must select the target-correct fixed-width type or use a C shim with an explicit fixed-width interface. Unknown target properties must be diagnosed rather than guessed.

19.4.2 Calling convention requirements

The target C ABI governs register/stack passing, result locations, scalar extension, and floating-point classification. In particular, small integers and _Bool must use the target's required argument and result extension rules; mapping every scalar to Int or assuming a raw LLVM i1 convention is not sufficient.

The source borrowing effect remains read-only access to the caller's value, but a C scalar crosses the native boundary by value. It does not pass a pointer to Joyeer storage or let C mutate the caller's binding. An export must adapt its incoming C values to the ordinary Joyeer function semantics; it must not expose incidental internal parameter or result layouts.

No implicit narrowing, sign change, integer/Boolean conversion, or integer/floating conversion is performed to repair a mismatched signature. Fixed-prototype calls do not apply variadic default promotions: Float remains C float. _Bool represents only false and true; it is not an arbitrary integer truth convention.

19.4.3 Restricted buffer imports

@c_extern additionally admits borrowing String, [UInt8], [String], and [[UInt8]], and initializing String, [UInt8], and [String]. These are explicit adapter conventions, not general C aggregate or pointer types. Results and @c_export signatures remain scalar/Void only. The array forms refer to the array_type role and its element type, never to the spelling Array or to an arbitrary three-word struct. The same identity governs native entry arguments main(args: [String]): Int, String.utf8() and the byte-pointer intrinsic below.

A borrowed buffer crosses as a read-only data pointer and signed 64-bit count. Strings and byte arrays count bytes; lists count elements and expose read-only runtime string/array descriptors. The native function must not mutate, retain, or free descriptors or backing storage. No encoding conversion or NUL terminator is implied. In particular, String is not a C string.

An initializing argument is passed by pointer to a caller-owned empty handle. The caller must provide uninitialized mutable owning storage with &. The adapter constructs a valid empty value before entering C. Native code may replace that value only with runtime-owned storage through the designated buffer assignment helpers, and must leave it initialized on every return, including failure. The caller then owns its ordinary destruction obligation. Foreign allocator storage must not be installed directly in such handles.

Exclusivity and initialization rules apply exactly as for ordinary Joyeer calls. Native declarations for one symbol must agree on buffer shape and access effect, not merely on the size of the flattened pointer arguments. Descriptor layouts, helper names, and runtime revision matching are defined in the buffer ABI implementation contract. There is no source-level raw-pointer value, asynchronous retention, callback, or general aggregate FFI in this extension.

19.4.4 Bare byte pointers

An import may pass a [UInt8] parameter as a bare data pointer, with no count. The annotation names it: @c_extern(symbol: "ReadFile", pointer: "buffer") names the parameter whose label is buffer. Each pointer: argument names a distinct parameter, and the parameter must be a [UInt8] that is borrowing or inout. Without pointer:, a borrowed [UInt8] keeps the pointer-and-count form of §19.4.3, and an inout [UInt8] is rejected.

For example, on supported POSIX targets read takes its byte limit as size_t:

@c_extern(symbol: "read", pointer: "buffer")
func nativeRead(descriptor: Int32, buffer: inout [UInt8], count: UInt64): Int64

A borrowed buffer crosses as const uint8_t*; an inout buffer as uint8_t* to the array's own storage, which native code may write in place. The count of bytes valid at that address is the array's count. The binding author must bound any native access to those bytes, whether its extent is fixed by the prototype or supplied as a scalar argument (§19.10). The native function must not retain the pointer, resize the array, or write beyond the count, and the compiler cannot check that it does not. An empty array may pass a null pointer. No string terminator is implied; see §19.10 for explicit adapters. Exclusivity and initialization rules for inout are those of ordinary calls. Repeated declarations of one symbol must agree on which parameters are bare pointers and on their access effects.

This lets a binding fill C structures laid out in a [UInt8] and read them back with ordinary indexing. For explicit address and length arguments, see §19.10. This form remains runtime-only and adds no source-level pointer value, address arithmetic, or dereference.

19.4.5 Compiler intrinsics

A C import whose symbol begins with joyeer_intrinsic_ names a compiler intrinsic. The compiler lowers it according to the table below and never links a symbol with the intrinsic's name. Every other rule for @c_extern applies unchanged: the declaration must be in a unit authorized for native bindings, so ordinary programs cannot use these. The symbol must be one of the table below, declared with exactly the listed parameter and result types; anything else with the prefix is an error, and @c_export of such a symbol is rejected. An address is an Int. The Declaration column lists each @c_extern declaration's labeled parameters and result in a shorthand; it is not a function type (§2.3.1), and intrinsics are not function values (§5.6.1).

SymbolDeclarationEffect
joyeer_intrinsic_address_of(bytes: inout [UInt8]) -> Int, with pointer: "bytes"The address of the array's first element. The parameter must be inout: a borrowed array may be a constant in read-only memory, and a store through its address would be undefined
joyeer_intrinsic_load_u8 / _u16 / _u32 / _u64(address: Int) -> UInt8 / UInt16 / UInt32 / UInt64Little-endian load of that width
joyeer_intrinsic_store_u8 / _u16 / _u32 / _u64(address: Int, value: UInt8 / UInt16 / UInt32 / UInt64) -> VoidLittle-endian store of that width
joyeer_intrinsic_atomic_add(address: Int, delta: Int) -> IntSequentially consistent add; returns the previous value
joyeer_intrinsic_atomic_add_relaxed(address: Int, delta: Int) -> IntAtomically adds modulo 2^64 and returns the previous value of the word. System scope, with no acquire, release, or sequentially consistent ordering
joyeer_intrinsic_atomic_load(address: Int) -> IntSequentially consistent load of an 8-byte word
joyeer_intrinsic_atomic_exchange(address: Int, value: Int) -> IntSequentially consistent exchange; stores value and returns the previous value
joyeer_intrinsic_atomic_cmpxchg(address: Int, expected: Int, desired: Int) -> IntSequentially consistent compare-and-swap: stores desired if the word equals expected; returns the value found (so it succeeded when that equals expected)
joyeer_intrinsic_call_void1(function: Int, first: Int) -> VoidCalls the C function at function, which returns void and takes one address argument, with the target's C calling convention
joyeer_intrinsic_call_void2(function: Int, first: Int, second: Int) -> VoidThe same for a function taking two address arguments
joyeer_intrinsic_literal_address(text: String) -> IntThe address of the NUL-terminated constant data of the string literal given as text, which must be a literal. No String value is created and nothing is allocated; it and symbol_address are the only uses of a string literal a core unit (§19.4.7) may make
joyeer_intrinsic_symbol_address(name: String) -> IntThe address of the function or data symbol named by the string literal given as name, which must be a literal (the same rules as literal_address). A function defined in the same program unit is taken directly; any other name is resolved by the linker, and nothing checks that it exists or what type it has. Used to store a runtime function as a callback
joyeer_intrinsic_static_slot(index: Int) -> IntThe address of 8-byte, zero-initialized slot index of a 64-slot table shared by every unit in the program; an index outside 0..<64 traps (static slot index out of range). Slots are 8-byte aligned, so atomic_add applies. Slot ranges are assigned in the runtime implementation notes
joyeer_intrinsic_memcpy(destination: Int, source: Int, count: Int) -> VoidCopies count bytes (taken as unsigned); the ranges must not overlap. No alignment is required. Lowers to LLVM's memcpy, so a small constant count becomes inline moves
joyeer_intrinsic_memmove(destination: Int, source: Int, count: Int) -> VoidThe same for ranges that may overlap
joyeer_intrinsic_memset(destination: Int, value: UInt8, count: Int) -> VoidStores value in count bytes
joyeer_intrinsic_double_bits(value: Double) -> UInt64The IEEE 754 bit pattern of value
joyeer_intrinsic_float_bits(value: Float) -> UInt32The IEEE 754 bit pattern of value
joyeer_intrinsic_syscall(number: Int, first: Int, second: Int, third: Int, fourth: Int, fifth: Int, sixth: Int) -> IntA Linux system call: number and the six arguments in the architecture's registers, the kernel's result returned unchanged (-4095 to -1 is a negated errno). Lowers to inline assembly (syscall on x86-64, svc #0 on AArch64); it is a diagnostic on any other architecture, and only a Linux program can run it. Decision 0011
joyeer_intrinsic_target_architecture() -> IntA constant: 1 for an x86-64 target, 2 for AArch64, 0 otherwise, so a runtime unit can choose the system call numbers of its architecture
joyeer_intrinsic_darwin_fcntl_int(descriptor: Int32, command: Int32, argument: Int32) -> Int32Calls Darwin fcntl(int, int, ...) with one C int vararg. Only for commands that take an int or no argument, such as the descriptor and status flags used by System. It is not a general variadic binding and only Darwin (macos and ios) uses it.
joyeer_intrinsic_darwin_openat_mode(path: inout [UInt8], descriptor: Int32, flags: Int32, mode: Int32) -> Int32Calls Darwin openat(int, const char *, int, ...) with one C int vararg for the promoted mode_t. path is a NUL-terminated byte pointer. Only Darwin (macos and ios) System uses it; this is not a general variadic binding.
joyeer_intrinsic_string_data(text: String) -> IntThe address of the bytes of the borrowed text, as a C binding receives them; meaningful only while text is alive and unchanged. The collections prelude's String operations build on it (0028)
joyeer_intrinsic_string_count(text: String) -> IntThe byte count of text

The generic layout intrinsics (joyeer_intrinsic_size_of, _align_of, _move_in, _move_out, _destroy_at, _stack_slot, _needs_destroy, _callback_address) are a separate family: they are not @c_extern imports and need no declaration (§20.12.5).

Non-atomic loads and stores need no alignment. The atomic operations require initialized, live, 8-byte-aligned storage, writable for operations that modify it. The relaxed add must not race plain or overlapping mixed-width accesses. Neither atomic add checks for signed overflow (§5.2). The operations assume a little-endian target; the supported targets are. An address from address_of is meaningful only while the array it came from is alive and unmodified in size, and the language does not track that. Nothing checks that an address points at memory the program may access: these operations can read and write anywhere, so a unit that uses them takes on the obligations of C. They exist so that the runtime itself can be written in Joyeer (decision 0005); they add no pointer type, no address arithmetic beyond Int, and no dereference syntax.

19.4.6 Runtime bulk memory and system calls

The bulk-memory and Linux syscall intrinsics are listed in §19.4.5. Byte comparison (memcmp) is not an intrinsic: LLVM has no inline form of it, so a runtime unit that needs it uses a target-provided native binding.

19.4.7 Core units, Never results, data symbols and the program entry point

A core unit, selected with --runtime-core-module <name> (which implies --runtime-module), may use only Bool, the integer and floating types, Void, Never, function types (§2.3.1) built from those, and top-level scalar constants. String, arrays, dictionaries, Optional, Result (ordinary prelude enums, §2.4, §2.5), other enums, structs, print and string literals (other than as the argument of the constant-data intrinsic) are reported as type-checking.managed-type-in-core-unit, because each lowers to a call into the runtime that the core unit is itself part of. None of this changes ordinary programs.

A C binding in any runtime unit may have the result type Never. On an import it declares a C function that does not return (exit); the call is followed by unreachable code and the declaration is noreturn. On an export it declares a Joyeer function that never returns (the runtime's panic); the C-callable entry is noreturn and does not return even if the body is mis-typed.

A data symbol is declared with @c_data(symbol: "name") on a bodyless func addressName(): Int with no parameters: the function's value is the address of that C data symbol, and nothing is called. It is a C import in every other respect: authorized units only, the symbol must be a C identifier and not a startup or intrinsic name, repeated declarations must agree, and one symbol cannot be both a function (@c_extern) and a data symbol. For a C variable that holds a pointer, such as glibc's stdout, the address yielded is the address of the variable, so the pointer is read with the load_u64 intrinsic.

Only a core unit may export the platform's program entry point: @c_export(symbol: "main") or "wmain", with the platform's C signature (Int32 argument count, then the argv address as an Int, returning Int32). Every other startup symbol (_start, mainCRTStartup, WinMain, DllMain, joyeer_main and the rest) stays rejected, in every unit. The IR carries a core flag so that the verifier enforces this too. A program that links a Joyeer entry point must not also link another one: the runtime archive is linked whole on Windows.

19.5 Invalid signatures

All types and parameter effects not admitted by §19.4 are rejected at this boundary. In particular:

In particular, String is not char*: its current implementation preserves arbitrary bytes, including NUL and invalid UTF-8. Neither a string's storage layout nor its longer-term text design grants a C-string conversion. An explicit adapter must follow §19.10.

19.6 Ownership, errors, and control flow

Scalar imports and exports do not transfer ownership of managed storage, allocate on behalf of the binding mechanism, or synthesize copy/destruction obligations. Their implementations may still allocate, perform I/O, fail, or have other side effects. No purity, thread-safety, retention, or error contract is inferred from a symbol's spelling.

Native error conventions remain explicit. A checked Joyeer wrapper translates status values into Result or other ordinary types; an annotation does not automatically inspect errno, Windows last-error state, sentinel values, or Boolean results. If a wrapper needs native error state, it must capture it before cleanup or another native call can overwrite it.

Neither direction permits a C++ exception, longjmp, or other nonlocal unwinding across Joyeer frames. Recoverable failures use the declared scalar protocol and explicit wrappers. A Joyeer panic retains its defined fatal behavior; it must not become a fabricated C success value or an exception escaping into C. Callbacks and asynchronous retention require separate designs. Entry from a foreign thread does too, with one exception: a function the runtime exports as a thread trampoline may be entered by a thread the runtime created through its thread API (decision 0016). Such a thread may allocate, print and panic (decision 0017), and nothing unwinds across the thread boundary.

The private Windows System read queue (decision 0032) passes addresses of its own fixed native records as scalar arguments to overlapped Winsock calls. It keeps those records allocated until every submitted completion has been dequeued, including after socket close. This does not allow native retention of any managed pointer: buffer or add an asynchronous binding or callback form.

The binding author must match the real native prototype and its behavioral contract. Without a header importer, checking the Joyeer declaration and finding a linker symbol cannot prove that the native definition agrees. A native contract violation is not made safe or recoverable by the annotation.

19.7 Linking and toolchain responsibilities

Source declarations specify callable signatures and C symbols. The build system supplies native objects, libraries, search paths, SDKs, target identity, and any required archive extraction or dynamic-export policy. Neither annotation locates a library, compiles C, imports a header, or adds a native dependency to a module manifest.

Toolchains may accept a concrete library artifact or a logical library name and search directories. Such inputs are build configuration, not part of a Joyeer native declaration; they do not grant native-binding authorization.

The selected provider may be static or dynamically linked without changing the declaration. Library selection and runtime search/deployment policy belong to the build target. Explicit runtime loading and symbol lookup (dlopen or LoadLibrary) are separate, unintroduced capabilities.

Missing required symbols, incompatible target inputs, and duplicate definitions are failures. No stub, alternate algorithm, or success-shaped fallback may mask a missing binding. An export creates a C-linkable entry in its object; it does not by itself force an archive member to be retained or a symbol to appear in a dynamic library's public export table.

Bindings lower to one typed native-binding model carrying import/export kind, C ABI, symbol, parameter/result representations, and source/module identity. Adding a binding with an already-supported signature must not require a new compiler special case for that particular C function. Preserve source spans for diagnostics and debugging through semantic checking, IR verification, and native emission.

C ABI compatibility is target-specific. This chapter does not promise a stable Joyeer binary-module ABI, a third-party runtime SDK, or identical layouts across platforms.

19.8 Required diagnostics

Implementations must report invalid annotation names/arguments, unauthorized use, invalid declaration placement or body presence, missing explicit types, unsupported signatures, conflicting symbol signatures, and duplicate exports as errors with source locations. Unknown semantic annotations must not be silently ignored as metadata. Native link failures must also be surfaced.

An incremental implementation may support fewer scalar types than §19.4 while development proceeds, but must diagnose every unsupported type instead of approximating its ABI. Its implementation documentation must identify that subset; passing the initial Int/Void gate does not establish full chapter support.

19.9 Specification examples

The identity example in §19.2 has these C11 prototypes:

#include <stdint.h>

int64_t joyeer_native_identity(int64_t value);
int64_t joyeer_rt_identity(int64_t value);

The scalar boundary also admits these declarations in an authorized runtime context:

@c_extern(symbol: "joyeer_native_ready")
func nativeReady(): Bool

@c_extern(symbol: "joyeer_native_sample")
func nativeSample(value: Float, scale: Double): Double

Their C11 prototypes are:

_Bool joyeer_native_ready(void);
double joyeer_native_sample(float value, double scale);

19.10 Scoped native memory

The existing authorized buffer forms and explicit wrappers are the native-memory boundary (decision 0038). A buffer adapter lends access to caller storage only for the call; it does not pin the storage or grant the callee ownership. Joyeer enforces source access and initialization, not the native prototype, extent, alignment, or lifetime. The binding author is responsible for those parts of the native contract.

The runtime's existing Int-address intrinsics and internal address carriers remain exceptions under §19.4.5 and §19.5. They do not introduce address types, address-taking or dereference syntax, nullable pointer values, or a public unsafe block. Neither the no-reference model (§4.8) nor the rejected C signatures in §19.5 change. Typed C callbacks, cross-thread borrows, foreign-thread entry, and retention of managed buffers are not admitted by this boundary. The runtime-only callback intrinsics (§19.4.5, §20.12.5) and the thread and native-storage exceptions in §19.6 are unchanged.