greycat-c
GreyCat C API and GCL Standard Library reference. Use for: (1) Native C development with gc_machine_t context, tensors, objects, memory management, HTTP, crypto, I/O; (2) GCL Standard Library modules
SKILL.mdplugins/greycat-c/skills/greycat-c
GitHubGreyCat SDK - C API, Standard Library & Plugin Development
Comprehensive reference for GreyCat native development (C API), the GCL Standard Library, and plugin development patterns. Tracks SDK 8.4 (headers re-verified 2026-10-18 against upstream 13ef7a6b1). Changes since 8.3 (C API additive except gc/stream.h signature changes (host params, durable → flush settings), gc_core_tensor__set_proxy's new ctx, gc_log_level_perf removal, the gc_core_* type-id globals removal, gc_sort__by_key's new prog param and three enumerator renames; breaking stdlib changes: S3/XML removal, sort null placement, log file moved to a stream, Log id renames, RuntimeUsage removal, perf level removal, metrics moved to their own streams, Stream buffering, String.chars()):
- Since
efb8395c4(breaking): C —gc_log_level_perfremoved,gc_log_level_tracenow4;gc_stream__registertakesu64_t flush_size, i64_t flush_step_us, gc_stream_format_t formatinstead ofbool durable,gc_stream__last_written_pos(host, s)gainedhost, newgc_stream__flush(host, s),gc_stream_format_t+GC_STREAM_DEFAULT_FLUSH_SIZE/_STEP_US,gc_stream__readermay return aCsvReader;gc_core_tensor__set_proxy(tensor, proxy, ctx)(marks the proxy);gc_env_options__host_perf_step→__metrics_host_step, 11 new options (__metrics,__metrics_http_fields,__log_flush_size/_step,__metrics_{http,host,task}_flush_size/_step,__log_flush_on_error). New:gc_geo_box_t+gc_geo_box__of/_contains/_bigmin/_litmax/_cells/_nth;gc_core_tensor_descriptor__same_shape/_shape_hash;GC_ABI_PRECISION_SIGNED+gc_abi_precision__step/_is_signed(@precisionfloats may be negative);gc_type_desc__generic_arg_fits;GC_CRYPTO_BASE64_DECODE_ERROR(decoders now refuse foreign bytes);GC_DTZ_ZONE_COUNT;gc_noinline;signbit(wasm). Map keys: any object, not copied;1and1.0one key. Stdlib —perf(v)/LogLevel::perfgone;TaskPerf/HostPerf*→TaskMetric/HostMetric*CSV streams (--metrics=host,task,http), newHttpMetric;Stream<T>::new(..., options: StreamOptions?)(buffered,flush(),StreamFormat::csv),reader(): Reader<T>;MergeStrategy+Task::set_merge_strategy,Mapmerges key by key;WorldChangesReader;String.chars()raw code points (old =nfkd_casefold_chars());nodeGeoranges/samplebox-exact. See api_runtime_storage.md, api_core.md, api_collections.md, api_services.md, standard_library.md. - Since
19f306db7— worlds (store branches): C —gc_env_options__worldsremoved (it sat before__port, so every later enumerator shifted down by one — ABI-breaking for stored raw offsets); newgc_env_options__world(.str,--world/GREYCAT_WORLD, NULL → main) appended beforegc_env_options_len;gc_periodic_options_tgainedu32_t world_id(offset 4, former padding; 0 = main; layout unchanged). Stdlib — newWorld(create(name, WorldMode),remove,id,current,list),enum WorldMode { full; light; },WorldInfo;world: String?onJob(spawn only —awaitjobs stay in the parent's world),Task,PeriodicOptions;StoreStats.worlds/StoreWorldStats. Also: newIdentity::create_with_password(sign-up),Identity::createon an existing name now keeps its password, emptyset_passwordremoves it. See api_runtime_storage.md, standard_library.md. - Since
e8eabaf84(breaking, C): theextern u32_t gc_core_any/_geo/_String/_Buffer/_Array/_Tuple/_Map/_Table/_Tensor/_TensorTypeglobals are gone — core type ids are now per program ingc_program_t.core(gc_program_core_types_t; nogeofield), filled by newgc_program__resolve_core_types(prog); readgc_machine__program(ctx)->core.Array. NewGC_CORE_MODULE_NAME/GC_CORE_TYPE_NAME_*macros.gc_sort__by_keygainedconst gc_program_t *prog(beforeallocator).gc/type.hno longer includes<stddef.h>. See api_core.md, api_services.md. - Since
e7630e693(breaking): C —gc_task_class_regular→gc_task_class_medium;gc_env_options__logfile→gc_env_options__reserved_2(--logfileremoved); newgc_env_options__cache_ratio_small/_large/__task_class(--cache_ratio_small0.4,--cache_ratio_large3,--task_classforgreycat call);gc_buffer__add_str_doubledremoved; newgc_sort__u64/gc_sort__u64_swap;gc_program_function+gc_program_tgained generic-type tables and opcodepush_obj_g(85). Stdlib —TaskClass::regular→medium;await(jobs)loststrategy,MergeStrategyremoved;Json<T>::parse(data)is static (+parse_tagged);Stream<T>::new/gettakeTfrom the call;RuntimeInforeshaped (per-classRuntimeInfoClass);Task::eventsstreams only the caller's own tasks;Runtime::backup_full(): String, newstore_stats(),Identity::remove/grant/revoke. See api_runtime_storage.md, api_core.md, standard_library.md. - Breaking (C):
gc_stream__append(host, s, record, len)— new leadinggc_host_t *host(the host the stream was registered on). Env enum:gc_env_options__usage_steprenamedgc_env_options__host_perf_step(same slot; default 60s; since renamed__metrics_host_step, see above); newgc_env_options__max_args_memory(--max_args_memory, 1 MiB — larger RPC args stream to the task's arguments file,Task::body()→null). See api_runtime_storage.md. - New: task classes + progress from C. Public
gc_task_class_t(small/medium/large;regularrenamedmedium);gc_periodic_options_tgainedu8_t task_classin former padding (layout unchanged, 24 bytes;{}gives small — set it). Newgc_task__expected_steps(ctx, n)/gc_task__add_steps(ctx, n). Stdlib:enum TaskClass,Job.task_class,PeriodicOptions.task_class,Task::task_class(), SSEtask-startedframe. See api_runtime_storage.md, standard_library.md. - Breaking (stdlib):
RuntimeUsage/WorkerUsage/ZoneUsage/Runtime::usage()removed →HostPerflog record;LogDataUsage→TaskPerf(once per task) — both since renamedHostMetric/TaskMetricand moved to their own streams;Log.id/id2→task_id/job_id. See standard_library.md. - New: JSON type tags.
gc_buffer_options_t.type_tag(write_typeon every object) andGC_COLOR_BRAND; stdlibJsonWriter.type_tag,JsonReader.type_tag/Json.type_tag: JsonTypeTag?(lenient/strict). See api_memory_text.md, standard_library.md. gc_program__create_function(program, mod_offset, type_offset, function_name_offset, *result_offset)now public;gc_program__create_from_abirebuilds symbols, type offsets, inheritance and exposed functions. See api_core.md.- Breaking (stdlib):
runtime::Requestremoved — itsheader/headers/uri/bodymoved toTask::(Request::x→Task::x;headers()nowMap<String, String>?,nullwhen the task answers no request). Every RPC call now runs as a task on tiered worker pools (visible inTask::running/history, cancellable;--request_ttlcancels queued/running RPCs with503). Env enum:gc_env_options__req_workersrenamedgc_env_options__workers_small(same slot/value — ABI-stable, source-breaking for code naming the old enumerator; CLI--req_workers→--workers_small/GREYCAT_WORKERS_SMALL); newgc_env_options__workers_large(--workers_large) appended beforegc_env_options_len. See api_runtime_storage.md, standard_library.md. - New:
gc_map__get_key(map, key, key_type, *stored_key_type, prog)— returns the map's own (deep-copied-on-insert) key object for a deep-equal probe key; borrowed, not marked. Needed to alias the key object the VM hands out when iterating a map (fix behind task suspend/resume of retained map keys). See api_collections.md. - New:
gc_time__join_us(epoch_s, us_offset)—static inlineinverse ofgc_time__split_us, recombining seconds + sub-second µs inu64_tto avoid signed-overflow UB attime::min. Use it instead of open-codings * 1000000 + us. See api_services.md. gc_slot__save/_save_value/_load/_load_valueare nowgc_sdk-exported (reliably linkable from plugins). Signatures unchanged. See api_memory_text.md.gc_env_options_offset_tgainedgc_env_options__openapi(GREYCAT_OPENAPI/--openapi, default on). Stdlib:OpenApi::v3()is now@permission("public")and, by default, documents every@exposed function (not just@tag("openapi")), filtered by the caller's permissions. See api_runtime_storage.md, standard_library.md.- New:
gc_program_type__inherits(prog, type, target_type_id)—trueiftypeinheritstarget_type_idat any depth, matching a bare generic through its monomorphized parent (likegc_program__is_type).gc_program_functiongainedbool is_raw(@raw: exposed result written astext/plain, not JSON). See api_core.md. - New:
GC_ARRAY_CELL_SIZE(bytes per element of the single slots+types block) in api_collections.md;gc_buffer_write_checkgained an inline fast path (same semantics) — api_memory_text.md. - Breaking (stdlib):
XmlReader<T>andS3/S3Bucket/S3Object/S3BasicCredentialsremoved fromstd::io. XML moved unchanged to thexmllibrary (@library("xml", ...)); S3 is a rewrite in thes3library (s3::Client,sigv4::Credentials, different method names) — existing S3 code must be rewritten. New stdlib: request accessheader/headers/uri/body(first asruntime::Request, now onTask::— see above;authorization/cookiehidden) andCrypto::equals_constant_time(a, b)for webhook signature checks. See standard_library.md. - New header
gc/stream.h(not included bygreycat.h) — public C API behindio::Stream<T>, allgc_sdk:gc_stream__register/_find/_append/_write/_reader/_last_written_pos/_name/_path/_typeover opaquegc_stream_t. Stdlib: newio::Stream<T>(append-only per-user NDJSON/CSV, batched callback withinmax_dephasing, buffered writes,flush()to sync). See api_runtime_storage.md, standard_library.md. - Breaking (stdlib): runtime log moved from
files/root/log.csvto thelogstreamfiles/root/streams/log.ndjson;Log.timelost@format(DurationUnit::microseconds). Read withStream<Log>::get("log").reader(from)/JsonReader<Log>. - Breaking (stdlib):
Array.sort/sort_by/Table.sortput null keys last in both orders;int/floatmixes sort numerically. C side: newgc_sort__by_key(out, count, key, key_ctx, asc, prog, allocator)+gc_sort_key_fningc/util.himplement exactly that. See api_services.md. - New
static inlinetime helpers:gc_time__join_us_checked(epoch_s, us_offset, *out)(bounds-checked join for untrusted instants,falseinstead of wrapping) andgc_time__utc_offset(epoch_us, localized_epoch_s)(floored UTC offset forgc_strftime_safe). See api_services.md. - New:
gc_buffer__add_function_name(self, fn, prog)(bare name, orGC_PROGRAM_LAMBDA_NAME="<lambda>");gc_program_function.name_off == 0marks a lambda / reserved slot 0. See api_memory_text.md, api_core.md. gc_env_options_offset_tgained__max_sse,__max_sse_per_user,__url,__token. Stdlib: newTask::events()— SSE stream onGET /runtime::Task::events(task-progress/task-completeframes), capped bymax_sse(2048) /max_sse_per_user(16). See api_runtime_storage.md, standard_library.md.
Previously, in 8.3 (headers re-verified 2026-09-16 against upstream 024068c6e):
- Breaking:
gc_mktime_safe's year-bound macros removed (GC_MKTIME_MAX_TM_YEAR,GC_MKTIME_MIN_YEAR,GC_MKTIME_MAX_YEAR). No replacement — code referencing any of the three no longer compiles. Not just dead-code cleanup: the year-at-a-time loop those macros bounded (±10000 years) was replaced by a constant-time closed-form inverse, sogc_mktime_safe's usable range widened to whatevertm_yearcan hold, fixingtime::min/time::maxround-tripping throughDate(ffa41d71d). See api_services.md. - New:
gc_time__split_us(epoch_us, *us_offset).static inlinehelper (no linking needed) that floor-divides a microsecond epoch into a whole-second count and a non-negative sub-second remainder — the shapegc_gmtime_r_safe/gc__print_isoexpect. Hand-rolled//%truncates toward zero, so it produced a negative remainder (rendering as.-500) for pre-1970 instants with a sub-second part; this is the fix behind GreyCat now reading back the ISO timestamps it writes (b12f39d05). See api_services.md. - New: incremental SHA-256 (
gc_crypto__sha256_init/_update/_done). Companion to the existing one-shotgc_crypto__sha256, for input that isn't contiguous in memory — a file read chunk by chunk, a stream._doneinvalidates the context; re-initbefore hashing again. See api_services.md. gc_buffer__add_type_name_by_idis back. Writes a type asmodule::Type(a specialized generic prints ascore::Array<core::int>); re-added after being removed in 8.2. Its two siblings,gc_buffer__add_type_nameandgc_buffer__add_type_qname, remain gone with no replacement. See api_memory_text.md.- New:
gc_machine__create/gc_machine__destroy, promoted from internal to public API — allocate/free a standalonegc_machine_tbound to agc_host_toutside the machine a native function normally receives from the host (e.g. a per-thread machine in a request-handling loop). See api_core.md. gc_env_options_offset_tgainedgc_env_options__registry/gc_env_options__registry_token— the registry URL and auth token for resolving libraries/releases viaGREYCAT_REGISTRY, a CLI feature; most plugin authors won't touch these. See api_runtime_storage.md.gc_object__is_instance_ofnow accounts for monomorphization — aBox<String>instance now tests true against the generic declarationBox, not just exact-type/inheritance matches as before. Signature unchanged. See api_memory_text.md.- Stdlib:
runtime::Log.timeis explicitly@format(DurationUnit::microseconds)— the field was always written as raw epoch microseconds by the log writer, now the type declares it instead of leaving it implicit. Readingfiles/root/log.csvwithCsvReader<runtime::Log>needsCsvFormat { string_delimiter: '\0' }, since the payload column is written unescaped. See standard_library.md.
Previously, in 8.2 (headers re-verified 2026-08-28 against upstream e1e7edf54):
- New:
gc_dtz_time__parse_format(str, len, format, format_len, tz, out_epoch_us)— parses a date/time string against an explicit format, the counterpart ofgc_dtz_time__printand the custom-format arm ofgc_dtz_time__parse. A format leaves the instant naive, sotzis the zone it is read in; returnsfalsewhen the input does not match the format, or names an instant the zone does not have. See api_services.md. - New: CLI hooks on
gc_program_library. Two optionalgc_hook_function_t *fields —installandcodegen— with settersgc_program_library__set_install_hook(lib, hook)andgc_program_library__set_codegen_hook(lib, hook). The install hook runs at the end of a successfulgreycat install(after the project is rebuilt and linked) for every library that registers one; returningfalsefails the command. The codegen hook makes the library itself a generator forgreycat codegen <lang>, dispatched by matching<lang>against library names (the built-inc/ts/java/rust/python2generators stay native to the CLI). Both are purely additive — aNULLhook opts out. See plugin_development.md, api_core.md. - New: resolved host configuration exposed to native libraries.
gc/env.hdefinesgc_env_slot_t(tagged-by-convention union:bool/i64_t/u64_t/f64_t/char *) andgc_env_options_offset_t(one variant per CLI/.env-resolved option, e.g.gc_env_options__port,gc_env_options__ca_path, terminated by the length markergc_env_options_len). The newgc_host__options(host)returns aconst gc_env_slot_t *array indexed by that enum, valid for the life of the host.gc/ca.h's newgc_ssl_ca__pem_bundle(u64_t *len)hands out the resolved TLS trust chain (system CA store +ca_path) as a PEM byte string, owned by the runtime — for libraries that verify their own TLS connections and want to honor the same trust config as the host. Both headers are pulled in automatically viagreycat.h. Full detail: api_runtime_storage.md. - New:
gc_machine__this_type(self)— thegc_type_tcounterpart togc_machine__this; returnsgc_type_undefined(and must not be called) when the current frame has no receiver. New:gc_abi__finalize_ex(abi)— releases everything a load allocated but notabiitself, for callers that own agc_abi_tinline rather than throughgc_abi__create. Both added for the Rust SDK rewrite. See api_core.md, api_runtime_storage.md. - Breaking:
gc_slot_tunion field order changed.u64_t u64is now the first member (previouslybool bwas first), to stop positional (non-designated) initializers from silently truncating throughbool. Any code using a non-designatedgc_slot_tinitializer ((gc_slot_t){x}with no.field =) now targets.u64instead of.b— designated initializers ({.i64 = x},{.object = p}, etc., used throughout this SDK's own examples) are unaffected. See api_core.md. - Breaking: three
gc/buffer.htype-name helpers removed, no replacement.gc_buffer__add_type_name,gc_buffer__add_type_name_by_id, andgc_buffer__add_type_qnameare gone from the header entirely (briefly exported, then removed again in the same cycle — never shipped as stable). Code calling any of the three no longer compiles. Every remaininggc/buffer.hfunction is now uniformlygc_sdk-exported (some previously lacked the export macro and could fail to link from a plugin shared library on strict-visibility builds) — this includes the pre-existing non-static inlinewriter functions (gc_buffer__write_u8/_bool/_u16/_u32/_u64/_u64_at/_f64/_vu32/_vu64/_vi64/_ptr), now reliably linkable from callers (e.g. FFI bindings) that can't call a Cstatic inlinefunction. See api_memory_text.md.
Previously, in 8.1 (headers re-verified 2026-08-04 against upstream 78e57676d): gc/buffer.h's read side was overhauled — every unchecked inline reader (gc_buffer_read_bool / _u8 / _i8 / _u16 / _u32 / _i32 / _u64 / _i64 / _f32 / _f64 / _vu32 / _vu64 / _vi64) was removed, replaced by bool-returning _size_checked equivalents; new gc_buffer_read_ptr_size_checked and GC_VU32_MAX_BYTES; gc_buffer_unavailable params are now const-qualified and it no longer special-cases NULL/underflowed cursors (breaking for any code relying on the removed void-returning readers or that fail-closed guard). gc/table.h's gc_table__init (param renamed table→self) now leaves the table untouched on allocation failure — callers must check self->capacity. Full detail: api_memory_text.md, api_collections.md.
Key Considerations
- Allocator API is mandatory. Every non-trivial allocation routes through an explicit
gc_allocator_t *: per-call scratch fromgc_machine__allocator(ctx)(=((gc_ctx_t *)ctx)->allocator), plugin-global state fromgc_host__global_allocator().gc_alloc__create(bool shared)(true= multi-thread arena).gc_alloc__free(a, ptr, size)requires the original size. The thread-boundgc_malloc/gc_free/gc_reallochelpers target whatevergc_alloc__bindset. New in 8.1:gc_alloc__reset(allocator)— destructively resets a whole arena (reclaims even leaked/lost pointers on the jemalloc path), invalidating every prior pointer from that allocator; use between iterations of a long-lived worker loop after tearing everything down, no-op on native-malloc/WASM/standalone. Sizing/stats and full patterns: api_memory_text.md. - Structured logging (
gc/log.h).gc_log_level_tisnone / error / warn / info / trace(perfremoved in 8.4,trace= 4 — rebuild code comparing raw levels; runtime metrics are separate streams behind--metrics). Usegc_log__machine/gc_log__machinef(VM context) andgc_log__host/gc_log__hostf(host context); gate hot paths withgc_log__enabled(host, level). - No inline short strings. There is no
gc/str.h:gc_str_tand thegc_core_str/gc_core_t2…t4fglobals are not public. Usegc_string_t(heap, immutable, hash-cached;bufferIS NUL-terminated atbuffer[size]— butsizeis still the authoritative content length, since the content itself may embed NUL bytes). gc_machine__call_functiontakes aconst gc_program_function_t *fn(not a raw body pointer). Onfalsethe result is a synthesizedErrorobject (typegc_core_Error) and*marked_res_typeisgc_type_object; the caller owns one mark on the result.gc_machine__impersonate(ctx, user_id)switches the effective user for permission-aware sub-calls.- Host/Scheduler (
gc/host.h).gc_host__cancel_task(self, task_id, requester_id, requester_permissions, out_task)is now thread-safe and permission-checked (out_taskoptional, receives a copy of the cancelled task);gc_host__get_task_statusstill takes justi64_t task_id.gc_host__spawn_tasktakes au64_t user_permissionsmask. Periodic scheduling viagc_scheduler_t,gc_periodic_task_t, andgc_periodicity_t(a struct holding agc_periodicity_type_t type: fixed / daily / weekly / monthly / yearly). New in 8.2:gc_host__options(self)(resolved CLI/env/.envconfig, seegc/env.h) andgc/ca.h'sgc_ssl_ca__pem_bundle(len)(resolved TLS trust chain). See api_runtime_storage.md. - ABI.
GC_ABI_PROTOis3.gc_abi_header_check_error_tincludes..._truncated = 4;gc_abi_tcarries its own allocator. New in 8.2:gc_abi__finalize_ex(abi)for inline-ownedgc_abi_tinstances (frees the load's allocations, notabiitself). gc_block_tgainedu64_t node_ref(new in 8.1) — the node reference the block backs, used by suspend/resume serialization to relocate the block's entries. See api_runtime_storage.md.- Iterator params
gc_program_iterator_param_t:from=0,to=1,nullable=2,from_excl=3,to_excl=4(nolimit). Geo epsilon constant isGC_CORE_GEO_EPS. - Tensor struct rename (breaking). The tensor structs are now
gc_tensor_t/gc_tensor_descriptor_t(formerlygc_core_tensor_t/gc_core_tensor_descriptor_t); thegc_core_tensor__*andgc_core_tensor_descriptor__*function names are unchanged, andgc_machine__init_tensornow takes/returns the renamed types. Plugin code that referenced the old struct typedefs must be updated. Full tensor API: api_collections.md. - Streams buffer (breaking, 8.4).
gc_stream__append/_write/ GCLwrite()only fill the stream's buffer (flushed atflush_sizebytes /flush_step_us, on reader /last_written_pos,/filesread, clean shutdown); a crash loses it. Callgc_stream__flush/Stream::flush()before persisting a drain offset.gc_stream__readerreturns the bare-generic reader, so GCL should useStream::reader()(aJsonReader<T>/CsvReader<T>). - Map key semantics (8.4).
gc_map__setaccepts object keys of any type and stores them uncopied (attached / marked shared; cloned only if owned by another block); keys hash withgc_slot__hashand compare withgc__deep_equals, which treatintandfloatof equal value as one key. Failed sets leave key/value untouched. - Geo boxes (new, 8.4).
gc_geo_box__of(a, b)+gc_geo_box__bigmin/_litmaxwalk only the Morton codes inside a box (whatnodeGeoranges andsamplenow do);gc_geo__encodeclamps out-of-range / NaN inputs. - Stdlib (GreyCat 8.0) breaking changes. Security model is
Identity/IdentityGrant/IdentityGrantType(the oldUser/UserGroup/SecurityPolicy/OpenIDConnecttypes are gone). GCL logging is via module-levelinfo/warn/error/tracefunctions (perfremoved in 8.4) —Logis a parse record, not a callable namespace. Remaining 8.0 surface (theHttpMethod/HttpRequest/HttpResponsemodel (HttpRequest.headersisMap<String, String>?,HttpResponse.headersisMap<String, String>),Csv::analyze(Array<String>),Uuidv4/v7, periodicity field shapes,LogLevel/TaskStatus/LicenseTypeenums): standard_library.md. ProgressTracker.update(nb)is now absolute, not incremental (breaking). It sets the step counter tonbrather than addingnbto it. New fieldsspeed_smoothed(EMA of the per-update pace) andsmoothing(EMA weight, defaultProgressTracker.DEFAULT_SMOOTHING = 0.1) drive a more reactiveremainingestimate. Also new since the last sync:HttpRequest.max_response_size(caps chunked/unbounded response reads) andTask::live(ids)/Task::tasks(ids)(bulk liveness check / bulk fetch by id).TensorDistancegainedlorentzandpoincare(hyperbolic distances — Lorentz/hyperboloid model and Poincaré ball model, both curvature fixed at -1).Identity.set_role(name, role)is a new admin-only static native — it returns nothing (void), notbool.- Other 8.0→8.1 signature/field changes.
gc_common__parse_number'sstr_lenparam widenedu32_t *→u64_t *(its siblinggc_common__parse_sign_numberis stillu32_t *— the two now disagree, match the local variable's type to the callee).gc_buffer_read_vu64_size_checkedadded (theu64_tcounterpart of the existing_vu32_variant), joined later in 8.1 bygc_buffer_read_vi64_size_checked(zig-zag signed) and theGC_VU64_MAX_BYTES(= 9) worst-case varint width constant.gc_object__clone,gc_array__fill, andgc_array__ensure_capacity(replacedgc_array__init; now grow-only/idempotent, rounds to a power of two, preserves contents) round out the collections/memory surface. Stdlib:Task.duration: duration?was replaced byTask.completion: time?,Taskgaineduser_name: String, andnodeGeo<T>gainedsearch(center: geo, max: int): Array<SearchResult<geo,T>>.
Contents
- C API - Native function implementation, tensor operations, object manipulation, maps, arrays, tables, geospatial, time/date, crypto, buffers, I/O
- Standard Library (std) - GCL runtime features, I/O, collections, and utilities
- Plugin Development - Complete guide to building native plugins with lifecycle hooks, type configuration, and real-world patterns
GreyCat C API
Core Concepts
gc_machine_t - Execution context passed to all native functions. Use to get parameters, set results, report errors, create objects, and access scratch buffers.
gc_slot_t - Universal value container (tagged union) holding any GreyCat value: integers, floats, bools, objects, enums, tuples, etc.
gc_type_t - Type system enum (8-bit, 24 values) defining all GreyCat types: null, bool, char, int, float, node variants, geo, time, duration, cubic, static_field, object, block_ref, block_inline, function, undefined, type, field, stringlit, error.
gc_object_t - Generic handle for heap-allocated objects. Packed to 128 bits. Every collection type (Array, Map, Table, Tensor, String, Buffer) starts with this as its first member.
Core Operations
The few patterns below are the trigger-level essentials. Full runnable examples for every operation (objects, tensors, arrays, maps, strings, buffers, allocators, logging, introspection) live in the five C-API reference files listed under Detailed Reference.
Parameters & results:
gc_slot_t p = gc_machine__get_param(ctx, 0); gc_type_t t = gc_machine__get_param_type(ctx, 0);
u32_t n = gc_machine__get_param_nb(ctx); gc_slot_t self = gc_machine__this(ctx); // instance methods
gc_machine__set_result(ctx, (gc_slot_t){.i64 = 42}, gc_type_int);
gc_machine__set_result(ctx, (gc_slot_t){.object = obj}, gc_type_object);
gc_object__un_mark(obj, ctx); // CRITICAL: every object result must be un-marked or it leaks / GC-faults
Enum parameters & results (CRITICAL — #1 native bug). GCL enum values are NOT gc_type_int; they are gc_type_static_field with the ordinal in .tu32.right (.tu32.left is the enum type offset), never .i64:
// WRONG — always hits the default fallback: (type == gc_type_int) ? slot.i64 : 0
// CORRECT:
i64_t variant = (gc_machine__get_param_type(ctx, 0) == gc_type_static_field) ? (i64_t) slot.tu32.right : 0;
// Returning MyEnum::variant2 (ordinal 1):
gc_machine__set_result(ctx, (gc_slot_t){.tu32 = {.left = 0, .right = 1}}, gc_type_static_field);
Errors: gc_machine__set_runtime_error(ctx, "msg") / gc_machine__set_runtime_error_syserr(ctx) (uses errno); check propagated errors with if (gc_machine__error(ctx)) return;.
Detailed Reference
The C API reference is split by domain — each file below is linked directly (one level deep) and loads on demand.
references/api_core.md — value model, execution context, type system, logging. Start here.
- Native C functions with
gc_machine_t(params, result, errors,gc_machine__allocator,gc_machine__impersonate,gc_machine__call_functionviagc_program_function_t *, object creation) gc_type_t/gc_slot_tvalue model, complex c64/c128 arithmetic,gc_node__parse- Program/Type system: linking (
gc_program__link_mod_fn/gc_program__link_type_fn), type configuration, introspection, iterator params, DurationUnit - Structured logging (
gc/log.h) and the cross-cutting Conventions & Patterns index
references/api_memory_text.md — memory, buffers, strings, objects
- Memory allocation: per-call, plugin-global, aligned, thread-bound helpers,
gc_alloc__create(bool shared), sizing/stats - Buffer building and binary read/write (varint, zig-zag encoding)
- Heap-allocated immutable strings (
gc_string_t, allocator-aware constructors) - Object/field manipulation, type introspection, GC mark/un-mark, serialization
references/api_collections.md — array, map, table, tensor
- Array, Map, Table get/set/add operations
- Tensors:
init_Nd, get/set/add for i32/i64/f32/f64/c64/c128, descriptor utilities, raw data access, matmul/bias/sum
references/api_runtime_storage.md — runtime, persistence, graph nodes
- Host/Task management (spawn, cancel, status), periodic scheduler (
gc_scheduler_t,gc_periodic_task_t), plugin-global allocator (gc_host__allocator/gc_host__global_allocator) - Storage blocks (attach/detach objects), ABI (allocator-aware, proto=3, truncated-header error, signed
@precision), file I/O (open/sync), streams (gc/stream.h, new in 8.4: buffered,gc_stream__flush, ndjson/csv), resolved env options (incl. metrics / flush settings) - Node resolution (
gc_node__resolve,gc_node__parse) and direct node-entry read/write (gc_machine_native__node_get/node_set_atviagc_node_single_value_t, released withgc_node_single_value__clear) — thisu64_t node_refAPI is uniform across all node variants (node, nodeTime, nodeList, nodeGeo, nodeIndex); only the key encoding differs per variant. Breaking in 8.1:node_getnow takes anexpected_type_id(gc_core_nodeTime/nodeList/nodeGeo/nodeIndex) beforectxand returns a null single plus actxruntime error if the resolved block is a different type
references/api_services.md — crypto, geo, time, math, util
- Cryptography (SHA-256, HMAC-SHA-256, Base64, Base64URL)
- Geospatial (geohashing, Haversine distance, geo boxes with BIGMIN/LITMAX); Time/Date/Timezone (formatting with
gc_dtz_time__print/parse) - Math (WASM shims, f64 PI/TAU/E/LN2 constants); Utility (Morton codes, hex, parsing, deep equality, sorting with allocator, licensing)
GreyCat Standard Library (std)
Module Organization
- std::core - Fundamental types (Date, Time, Duration, Tuple, Error, geospatial types, enumerations)
- std::runtime - Scheduler, Task, Job, Logger, Identity/Security, System, ChildProcess, current HTTP request (
Task::header/body/...), License, OpenAPI, MCP - std::io - Text/Binary I/O, CSV, JSON, HTTP client, Email/SMTP, FileWalker, Stream (new in 8.4) (XML and S3 moved to the
xml/s3libraries in 8.4) - std::util - Collections (Queue, Stack, SlidingWindow, TimeWindow), Statistics (Gaussian, Histogram, GaussianProfile), Quantizers (Linear/Log/Custom/Multi), Assert, ProgressTracker, Crypto, Uuid, Random
Detailed Reference
File: references/standard_library.md
Load when working with:
- Task scheduling and automation (Scheduler with periodicities)
- File I/O operations (CSV, JSON, binary files)
- HTTP integration and REST APIs, webhook request inspection (
Task::header/Task::body) - Statistical analysis and data processing
- Identity, security, and authentication
- System operations and logging
Contains: Complete documentation for all four standard library modules with code examples, usage patterns, and best practices.
Plugin Development Guide
Overview
Build native GreyCat plugins in C with proper lifecycle management, type configuration, and thread safety.
Key Patterns
Function naming (CRITICAL — must match nativegen): gc_<module>_<Type>__<methodName>(gc_machine_t *ctx)
When GreyCat compiles GCL code with native declarations, it auto-generates nativegen.c / nativegen.h. Those extern declarations define the exact C symbol names the runtime resolves at dlopen — your C definitions MUST match or you get undefined symbol errors. Convention:
- Type method:
gc_<gcl_module>_<GclType>__<methodName>(double underscore before the method) - Module function:
gc_<gcl_module>__<functionName>(double underscore before the function) <gcl_module>is the GCL file's module path;<GclType>matches the GCL type (PascalCase);<methodName>matches the GCL method (camelCase)
// GCL (module "text_normalizer", type TextNormalizer):
// native static fn rejoinHyphenatedWords(text: String): String;
// nativegen.h generates:
// extern void gc_text_normalizer_TextNormalizer__rejoinHyphenatedWords(gc_machine_t *ctx);
// Your C implementation MUST be named exactly:
void gc_text_normalizer_TextNormalizer__rejoinHyphenatedWords(gc_machine_t *ctx) { ... }
Plugin lifecycle: link -> lib_start -> [worker_start -> native calls -> worker_stop] -> lib_stop
Type configuration: gc_program_type__configure(prog, type_id, sizeof(my_struct_t), finalizer)
Library hooks:
gc_program_library__set_lib_hooks(lib, lib_start, lib_stop);
gc_program_library__set_worker_hooks(lib, worker_start, worker_stop);
gc_program_library__set_install_hook(lib, lib_install); // optional: end of `greycat install`
gc_program_library__set_codegen_hook(lib, lib_codegen); // optional: `greycat codegen <lang>`
Detailed Reference
File: references/plugin_development.md
Load when:
- Building a new native plugin from scratch
- Setting up CMake build configuration for .gclib output
- Implementing nativegen.c/h (symbol resolution, type/function linking)
- Linking module-level native functions (gc_program__link_mod_fn) or type methods (gc_program__link_type_fn)
- Managing library/worker lifecycle hooks
- Wrapping C library handles in GreyCat objects (boxing pattern)
- Implementing thread-safe global state with mutexes
- Mapping GCL enums to C library enums
- Using the buffer reuse and tokenization retry patterns
- Implementing conditional logging (gc_machine__log_level / gc_log__enabled)
Contains: Complete project structure, CMake configuration, GCL type definitions, nativegen implementation, lifecycle hooks, custom type configuration with finalizers, global state management, memory management patterns, parameter handling (including type checking with gc_object__is_instance_of), result returning, error handling, conditional logging, and a full end-to-end plugin example.