Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Welcome to the Co Programming documentation.

Co is still under active development, so its core features may be revised along the way. This document is the authoritative baseline for the final feature set.

This document is the foundational specification of Co. All language features of Co are defined against this document. Before reading it, please make sure you already have a programming background in other languages; this document mainly explains Co’s language features and is not a beginner’s programming tutorial.

Co is a new language extended from C. It stays as compatible as possible with existing C syntax rules, and additionally supports some object-oriented features. It can be roughly understood as Co ≈ C + object, or a simplified C++.

The default file extension of Co source files is .co.

All current syntax of Co is based on C, so anything not covered in this document follows the current C standard (C23 recommended, i.e. ISO/IEC 9899:2024). Wherever Co conflicts with or extends C, this document will describe it as clearly as possible.

Getting Started with Co

This chapter walks you through two minimal examples: one prints a greeting to the console, the other pops up a Windows message box. Both use only the basic forms already described above and need no extra project setup.

Minimal Console Example

The program below prints a greeting directly from the top level and then ends. It demonstrates the simplest Co language example.

printf("Hello, Colang!\n");

Minimal Windows GUI Example

The program below is a UI example: it pops up a message box in the entry point, and the process exits when the user closes it. It shows how to import prototypes and constants from winapi.co with import, the GUI entry point, and how a message box is called.

[[subsystem("windows")]]
import * from winapi;
MessageBoxA(0, "Hello, Colang!", "Colang GUI", MB_OK | MB_ICONINFORMATION);

Program Entry and Execution

This chapter describes Co’s program entry and execution model. Entry dispatch, optional main, top-level return and the exit-code model are implemented since V0.2.0; cross-module (import) top-level execution in a centralized topological order is implemented since V0.3.0; the Windows GUI entry WinMain and the [[subsystem("windows")]] subsystem switch are implemented since V0.3.1; the top-level built-in command-line argc/argv are implemented since V0.5.5 (see “Command-line arguments”).

Top-level statements run in order

A Co program starts at the “top level”: in a .co file, the commands written outside definitions of functions, types, and so on (top-level bare statements) run in the order they appear in the source. You do not have to write a main function to serve as the entry point.

With or without main

To stay compatible with C-style code, Co accepts both kinds of program:

  • No main: the program simply runs its top-level statements in order, then ends.
  • With main: main is an ordinary function, entered only after all top-level statements have run.

GUI entry (WinMain)

Besides the console entry of “top-level statements / main”, Co also supports the Windows GUI entry WinMain:

int WinMain(void* hInstance, void* hPrevInstance, char* lpCmdLine, int nCmdShow)
{
    // create the window, run the message loop...
    return 0;
}
  • Fixed signature: four parameters, returning int (the ANSI form; the wide variant wWinMain is not yet supported). The return value is the process exit code.
  • Defining WinMain automatically takes the GUI entry: the artifact is a Windows GUI subsystem program (no console window), with no command-line flag needed.
  • To drop the console while keeping the main/top-level entry, mark the entry function with [[subsystem("windows")]] (see the “Attributes” chapter).
  • WinMain is mutually exclusive with top-level bare statements: a file with both WinMain and top-level bare statements is a compile error (put the GUI logic inside WinMain); WinMain must take exactly 4 parameters, otherwise the compiler errors.

Process exit code

The number the program returns to the operating system when it ends (the exit code) is determined as follows:

SituationExit code
A top-level return V; is reachedV, and the whole program ends immediately (later top-level statements and main are not run)
Top level finishes with no return, and a main existsmain’s return value
Top level finishes with no return, and no main exists0
A bare return; (no value)0

Key point: a return at the top level ends the whole program (not some function), so it skips main; a return inside a function body still ends only that function (see the “Function Definition” chapter).

Command-line arguments

Since V0.5.5, the .co top-level entry (the case where you do not write main and the compiler synthesizes the console entry) can directly reference two compiler built-in names, argc and argv:

  • argc is an int, the number of arguments (including the program name itself, so argc >= 1);
  • argv is a char** (a pointer to strings); argv[0] is usually the program’s own path, followed by the arguments in order;
  • iterate by the argc count; argv[argc] is always NULL (guaranteed by C). argv is a raw pointer, carries no length property, and has no bounds checking (C semantics) — keep within range using argc yourself;
  • both are scoped to the synthesized entry’s top-level code: referencing argv in a .c file, in a shared-library artifact (-o *.dll / *.so), or under the GUI WinMain entry makes the compiler report an undeclared identifier.
// hello.co -- no main, read argc/argv directly at the top level
int i = 1;              // start at 1, skipping argv[0] (the program name)
while (i < argc)        // iterate by the argc count, do not probe past the end
{
    // handle argv[i] (e.g. argv[i][0] for its first character)...
    i = i + 1;
}
return 0;

If you write an explicit main (C style), arguments still arrive as its parameters, per C convention: int main(int argc, char** argv).

Planned: making argv a globally visible, self-length-carrying string-array value type (readable inside functions and methods, with no argc) depends on Co’s array-carries-own-length infrastructure (same batch as string/general arrays) and is not yet provided; for now it ships as the C-form argc + char**.

When there is no executable entry

If a program has neither top-level statements nor main (there is genuinely nothing to do) and the target is an executable file: the compiler issues a warning and produces an empty executable that does nothing and exits with code 0 — the build still counts as successful. This rule does not apply when building a dynamic / static library (a library never requires an entry point).

Cross-module execution timing

Since V0.3.0, when a program consists of several modules (.co files) that import one another, each module’s top-level statements follow:

  • Exactly once at first load: no matter how many times a module is imported, its top-level code runs only once.
  • Centralized topological order: all imported modules’ top-level statements are emitted before the main entry, arranged in DFS-postorder of the dependency closure (dependencies run before dependents). The physical position of import lines in the main source has no effect on this order.
  • main of a non-main module is not a load hook: if a module defines main, it is treated as an ordinary function symbol and does not execute automatically.

See the “import (Module Import)” and “Module” chapters for details.

Currently implemented boundary

Since V0.2.0, entry dispatch and exit-code behavior are implemented as specified above:

  • When a file contains top-level bare statements, the compiler synthesizes an entry and runs the top level in source order; if a user-defined main also exists, main is entered automatically after all top-level statements finish, and main’s return value becomes the exit code.
  • return V; at the top level ends the whole program immediately with exit code V; a bare return; uses exit code 0.
  • A file with neither top-level bare statements nor main: when producing an executable, the compiler warns and still emits an empty entry that does nothing and exits with code 0.
  • Pure C style (no top-level bare statements + a main) keeps the traditional C entry chaining and does not enter the synthesized entry.
  • Windows GUI entry (since V0.3.1): defining WinMain in the source takes the GUI entry (no console); or mark the entry function with [[subsystem("windows")]] to switch to the windows subsystem. WinMain is mutually exclusive with top-level bare statements and must take 4 parameters.
  • Command-line arguments (since V0.5.5): the .co top-level entry (synthesized console main) has built-in argc(int)/argv(char**), iterated by the argc count with argv[argc]==NULL; valid only as built-in names in the synthesized entry’s top-level code (referencing argv in .c/-o *.dll/*.so/WinMain reports undeclared); an explicit main (pure C style) still receives argc/argv as parameters.

Not yet provided:

  • argv as a globally visible, self-length-carrying string-array value type (readable in functions/methods, no argc needed) is not yet provided; it depends on the array-carries-own-length infrastructure (D37, same batch as string/general arrays). For now it ships only as the C-form argc + char** top-level built-in names.

Function Definition

Syntax

[ public ] TYPE FUNCTION_NAME([TYPE ARG1, ...])
{
	segment
	return VALUE;
}

Description

(This section describes only the externally observable semantics and behavior of functions. Their internal implementation mechanism is outside the scope of this document.)

A function definition has four parts: the return type TYPE, the function name FUNCTION_NAME, the parameter list, and the function body. A function name is unique within its module; return VALUE; hands back the result and ends the call.

Return type

  • The return type must be written explicitly. Co does not accept the early-C “implicit int” convention (omitting the type meaning int); a function definition without a return type is rejected.
  • void means the function returns no value. void may be used only as a function’s return type and cannot be used as the type of a variable or a parameter.
  • A function may return integers, floating-point values, pointers, struct values, class references, and so on. An array cannot be returned directly (to return an aggregate, wrap it in a struct, or hand back a pointer).

Parameters

  • Each parameter is written as TYPE ARG_NAME; parameters are separated by commas.
  • When a function takes no parameters, the parameter list may be written as () or (void) — the two are synonyms; such a function must not be called with any argument.
  • A parameter is a local variable inside the function: its scope is the function body only, and it never interferes with same-named variables outside.
  • Array parameters are treated as pointers: both int a[] and int a[10] are equivalent to int *a, so sizeof(a) inside the function yields the pointer width, not the array length.
  • A variadic function ends its parameter list with ... and reads the arguments through va_start / va_arg / va_end from <stdarg.h>.
  • Default argument values are not supported, nor are reference parameters (such as int &x). Arguments are always passed by value; to let a function modify the caller’s data, pass a pointer.

Visibility and export

public is Co’s keyword for making something external. It carries both the “module interface” and the “dynamic library export” meanings at once (there is no separate export); private may appear as an explicit spelling of omitting public, with the same external/cross-module meaning as omitting public and no added restriction (the only place Co enforces an access restriction is class property accessors — see the “class” chapter). The table below is stated in terms of public:

FormMeaning
[ public ]The function joins its module’s external interface and can be used by other modules; when a dynamic library is built, it enters the export table
public omittedThe function is visible only inside the module that defines it; other modules cannot reach it and it is not exported

Definition order and recursion

Co does not require “declare before use”: functions within the same module may reference each other regardless of writing order, so recursion — and two functions calling each other (mutual recursion) — needs no forward declaration. Writing a forward declaration (a prototype) is still allowed, and the parameter names in a prototype may differ from those in the definition.

Returning and return

  • A function whose return type is not void must produce a value before it finishes.
  • A void function may omit return entirely, or use a bare return; partway through to end early.
  • Inside a function body, return ends only that function. Top-level (file-scope) return, the process exit code, and program execution order are a program-level model; see the “Program Entry and Execution” chapter.
  • A void function must not return a value, and a non-void function must not write a bare return;. The compiler rejects both.
  • A function body may contain several return statements (commonly used for early exits on conditions).

Example

The example covers public, void, recursion, variadic arguments, and the “used before defined” writing order:

#include <stdarg.h>

public int add(int a, int b)
{
    return a + b;
}

void greet()
{
    printf("hello\n");            // void function, no return written
}

int fact(int n)
{
    if (n <= 1)
        return 1;                 // early exit on condition
    return n * fact(n - 1);       // recursion
}

int total(int n, ...)
{
    va_list ap;
    int i;
    int s = 0;
    va_start(ap, n);
    for (i = 0; i < n; i++)
        s = s + va_arg(ap, int);
    va_end(ap);
    return s;
}

// Uses may precede the definitions, as long as they are in the same module
printf("%d\n", add(1, 2));            // 3
greet();                               // hello
printf("%d\n", fact(5));              // 120
printf("%d\n", total(3, 10, 20, 30)); // 60

Relationship to C / C++

AspectCoCompared to
Typed parameters, pass by value, returninheritedsame as C
static / extern storage classes, function pointersinheritedsame as C
Definition orderirrelevant; a call may precede the definitiondiffers from C (C requires a prior declaration)
Omitting the return typenot allowedsame as C (implicit int was removed in C99)
Empty parameter list ()means “takes no parameters”, synonym of (void)differs from C (in C () leaves the parameters unspecified)
Overloading, default arguments, reference parameters, function templatesnot provideddiffers from C++
publicexpresses “module interface / export”, not an access regiondiffers in meaning from C++’s public

Compatibility note: In Co, () and (void) are synonyms — neither accepts any argument. When migrating from C, code that relies on f() leaving the parameters unspecified so that any arguments may be passed does not hold in Co.

Current boundaries (compiler implementation status)

Since V0.3.0:

  • public on top-level functions / global variables is implemented: lexer / parser / sema are wired, and when the artifact is a dynamic library the symbol is written into the export table (DLLExportStorageClass); static public in either order is legal. Since V0.3.0, public also serves as the sole cross-module visibility gate: symbols not marked public cannot be reached by import (both named and * forms report cannot import non-public symbol); non-public imported symbols are forced to InternalLinkage during codegen. In this batch, public still does not change linkage within the same TU (non-public remains ExternalLinkage by default, matching P211); “module-internal” is still expressed by omitting public (see the “Module” and “import” chapters).
  • Sequential execution of top-level commands is implemented (entry dispatch, optional main, top-level return and exit code) — see the “Program Entry and Execution” chapter for the full model.

Reserved names

main and the function names already declared by the standard library (such as printf) should not be reused for your own functions. The four Co lifetime protocol names (__new__, __retain__, __release__, __delete__) are reserved and must not be used as function names.

Attributes ([[...]])

Syntax

Co adopts the C23 attribute spelling: a pair of brackets [[ ]] encloses one or more attributes, separated by commas, written before a declaration:

[[ ATTRIBUTE1, ATTRIBUTE2(...) ]]  declaration

Five attributes currently carry meaning in Co:

AttributeApplies toEffect
[[lib("X")]]top-level function declarations, global variable declarationsdeclares that the symbol is supplied by external library X; the linker pulls X in automatically
[[deprecated]], [[deprecated("message")]]top-level functions, global variablesemits a warning at each reference to the symbol
[[nodiscard]], [[nodiscard("reason")]]functions with a return value (prototypes included)warns when a call’s return value is discarded in statement position; an explicit (void)f() does not warn
[[noreturn]]void functionsverifies the function never returns: both a return in the body and falling off the end warn; call sites are treated as non-returning
[[subsystem("windows")]]entry function (main / WinMain)switches the linked artifact to the Windows GUI subsystem (no console)

[[ is the only spelling; the <: ::> alternative token spelling from C is not supported by Co.

[[lib("X")]] — declaring library ownership

Which library implements an external function (such as an OS API) had no way to be expressed: writing only a prototype without telling the linker the library name makes the link fail with an undefined symbol. [[lib("X")]] supplies that ownership:

[[lib("user32")]] int GetSystemMetrics(int nIndex);
[[lib("user32")]] unsigned int GetDoubleClickTime(void);

public int screen_width()
{
    return GetSystemMetrics(0);   // no -luser32 on the command line; the linker pulls user32 in
}

X is a link name (no extension, path, whitespace, quotes, or colon), completed by the linker for the target platform, spelled the same as on the -l command line. So "user32" is valid, while "user32.lib", "", "sub/user32", and "C:x64/user32" are all rejected.

Constraints:

  • .co/.CO source files only: [[lib]] is a Co-defined attribute, so any other origin — a .c/.h file, including a header #included by a .co — is rejected with 'lib' attribute is only allowed in .co source files. The check looks at the file the attribute actually appears in; a .h is not relaxed just because a .co includes it. Putting library ownership in a shared header for several .co files to consume therefore does not work — it must be written inside the .co.
  • Only on declarations: a function must be a pure prototype (no body), and a global variable must be a pure external declaration (no initializer). Claiming a symbol comes from an external library while also writing its definition in this module is a contradiction, which the compiler rejects.
  • Mutually exclusive with public and static: public is export, lib is import — they cannot fall on the same symbol; static means internal linkage, which an external library cannot supply.
  • Same-name symbols must agree on their library: re-declaring the same name with the same library is legal; giving the same name two different libraries is an error (no silent choice is made).
  • Writing two [[lib]] attributes on one declaration is an error.

[[deprecated]] — marking something deprecated

Marking a function or global variable with [[deprecated]] emits a warning at every later reference, nudging callers toward a different interface; a message can name the replacement:

[[deprecated]] int old_add(int x);
[[deprecated("use new_api instead")]] int new_api(int x);

int use(int x)
{
    return new_api(x);   // warning: 'new_api' is deprecated: use new_api instead
}
  • When the attribute is on a forward declaration and the definition is written elsewhere, they merge by the same entity — the call site still warns.
  • Repeated annotations at the same position are accepted idempotently (e.g. [[deprecated, deprecated]], or two adjacent attribute lists); the first message written wins (first-wins) and later duplicates are ignored — the same rule clang follows.
  • Warnings do not change the program’s exit code and do not block compilation.
  • deprecated on a declaration in local scope is not effective at present.

[[nodiscard]] — the return value must not be discarded

Marking a function with a return value as [[nodiscard]] produces a warning whenever a call discards its result in statement position; a reason can spell out what the caller should do:

[[nodiscard]] int check(int x);
[[nodiscard("handle the result")]] int compute(int x);

int run(int x)
{
    check(x);                 // warning: ignoring return value of function declared with 'nodiscard' attribute
    compute(x);               // same warning, trailing the reason: : handle the result
    (void)check(x);           // explicit discard counts as intentional — no warning
    return check(x) + 1;      // using the value — no warning
}
  • The warning text matches clang (-std=c23); with a reason, the trailing : reason is kept verbatim.
  • A prototype alone (a declaration without a body) already takes effect: prototypes and definitions register as the same entity.
  • Marking a function without a return value (void) is an error: attribute 'nodiscard' cannot be applied to functions without return value.
  • Repeated annotations at the same position ([[nodiscard, nodiscard]]) are accepted idempotently, same as clang.

[[noreturn]] — declaring that a function never returns

Marking a void function [[noreturn]] makes the compiler verify it truly never returns: a return appearing in the body warns (each occurrence), falling off the end of the body warns once more, and call sites are treated as non-returning — dead code after the call no longer triggers spurious “missing return” complaints:

[[noreturn]] void bail(void);

int work(int c)
{
    if (c)
        bail();               // call site treated as non-returning
    return 0;                 // no spurious "not all paths return a value"
}
  • The warning text matches clang: function 'h' declared 'noreturn' should not return.
  • [[_Noreturn]] is the deprecated C23 spelling; Co accepts it as synonymous with [[noreturn]] (without emitting an extra deprecation warning for the old spelling).
  • Again, only the annotation matters, not the writing order: marking a prototype registers it; repeated annotations are accepted idempotently.

By default Co produces a console-subsystem program (it opens a console window at runtime). Marking the entry function with [[subsystem("windows")]] switches the linked artifact to the Windows GUI subsystem (no console window):

[[subsystem("windows")]]
int WinMain(void* hInstance, void* hPrevInstance, char* lpCmdLine, int nCmdShow)
{
    // create the window, run the message loop...
    return 0;
}

There are only two possible values:

  • "windows": Windows GUI subsystem, no console.
  • "console": console subsystem (an explicit spelling, equivalent to not marking it).

Constraints and key points:

  • Only takes effect on the entry function (main or WinMain); marking it on any other function emits a warning (without blocking compilation).
  • Writing two [[subsystem]] attributes on one declaration is an error; a value that is neither "windows" nor "console" is an error.
  • Defining WinMain already implies the windows subsystem; you need not also write [[subsystem("windows")]] (writing it does not conflict).
  • See the “Program Entry and Execution” chapter for more on entry points and WinMain.

Feature probing and unrecognized attributes

The preprocessor directive __has_c_attribute(name) returns 1 or 0 and can drive conditional compilation:

#if __has_c_attribute(lib)
[[lib("user32")]] int GetSystemMetrics(int nIndex);
#endif
  • Known attributes that still carry no effect (maybe_unused, fallthrough, and others) are accepted silently — no error, no warning — so that code migrated from C/C++ is not disturbed.
  • An unrecognized bare name emits one unknown attribute 'x' ignored warning and is skipped, without blocking compilation.
  • A namespaced attribute name (such as [[colang::lib]]) is rejected with an error: Co does not pretend to support vendor attributes it cannot honor.

Relationship to C / C++

AspectCoCompared to
Attribute spelling [[...]]adopted from C23same as C23
[[deprecated]]supported (diagnostic layer, not in the artifact)matches C23 semantics
[[nodiscard]] / [[noreturn]]first batch of semantics in effect (warnings and verification, clang-shaped)largely matches C23 (type-level marking etc. see below)
[[maybe_unused]] / [[fallthrough]]accepted but no effectdiffers from C23 (C23 has real semantics)
[[lib("X")]]newly defined by Co; no such attribute in the C standard; and .co/.CO source files onlyCo-specific
[[subsystem("windows")]]newly defined by Co; no such attribute in the C standardCo-specific
<: ::> alternative spellingnot supporteddiffers from C23

Compatibility note:

  1. [[lib("X")]] is a Co-defined attribute. When a real clang/clangd reads .co files, it warns -Wunknown-attributes and ignores it — this is necessarily so, not a defect; external tools will not validate library ownership, only the Co compiler consumes it.
  2. When migrating from C/C++, #pragma comment(lib, "X") and __declspec(dllimport) are neither implemented nor simulated by this compiler; library ownership must always be rewritten explicitly as [[lib("X")]]. And [[lib]] can only be written in .co files — a pure .c translation unit names its external libraries on the command line with --lib <name> instead (see the “Command Line” chapter), with no need to move declarations into a .co.
  3. [[deprecated]] is a front-end diagnostic only; like clang, Co does not encode it into the artifact’s IR, so it does not propagate to downstream modules that consume the artifact.
  4. [[subsystem("windows")]] is likewise a Co-defined attribute: a real clang/clangd warns and ignores it as an unknown attribute (necessarily so, not a defect); only the Co compiler consumes the subsystem switch.

Vendor-compatibility extension: __attribute__ (GCC/Clang)

Qualification (added solely for compatibility): the syntax in this section is not ISO C (no such spelling exists in C89–C23; the standard attributes are the [[...]] of the previous section) and is not a Co dialect feature. It exists purely to be compatible with existing source code coming from GCC/Clang — so such code need not be rewritten site by site just to compile — and is not part of Co’s language design. For newly written code, prefer the C23 [[...]] attributes and _Alignas(N); do not rely on __attribute__.

Co accepts the GNU __attribute__((...)) spelling and handles it in tiers:

  • aligned(N) — given real semantics: it raises the alignment of an object / member / struct·union type / typedef (observable via sizeof, _Alignof, offsetof), matching the local clang -std=c23 verbatim. It is a one-way promotion only: alignment becomes max(natural alignment, N) and is never lowered. N must be a power of two, otherwise it is an error (same as clang).
  • packed — given real semantics (since V0.5.0): applied to a struct/union type or to a field, it really changes sizeof, _Alignof, offsetof and the emitted layout (members without an explicitly declared alignment are laid out compactly at 1 byte), matching the local clang -std=c23 value for value. Four boundaries, stated as they are: (1) an explicitly declared alignment wins — the member’s own _Alignas(N), or a type-level aligned(N) carried by the member’s type, still aligns that member to N (packed only compresses natural alignment, never an explicit one); (2) it binds only where it really takes effect — between the struct/union keyword and its tag name, after the closing }, and after a field name; written before the declaration specifiers, after a variable name, after a typedef name, on a parameter, on a function, or between the tag name and { it has no effect and emits the same ignore warning clang does ('packed' attribute ignored / attribute 'packed' is ignored, place it after "struct" …, where struct follows the keyword); (3) packed does not recursively rewrite the internal layout of an already-defined nested type; (4) together with bit-fields it really takes effect — a bit-field’s storage unit keeps the width of its declared type (int : 4 still occupies 4 bytes / an i32) and packed only compresses the unit’s placement alignment to 1; a zero-width :0 merely closes the current unit, occupies no space and contributes no alignment; a change of unit type (or an overflow) opens a new unit (e.g. struct { unsigned a : 3; unsigned b : 5; char c; } is 5/1 with packed and 8/4 naturally, matching the local clang value for value). The separate #pragma pack path has real layout effects as well, since V0.5.0 (see “Current boundaries” for its stack semantics).
  • Every other attribute — syntax accepted, semantics ignored, a warning emitted, in two levels by risk:
    • Strong warning (may affect memory layout / calling convention / linkage): the calling-convention family (stdcall / cdecl / fastcall / thiscall / vectorcall), section, weak, alias, dllimport / dllexport, constructor / destructor, and the like (packed has had real semantics since V0.5.0 and no longer belongs to this tier). Text shaped like gnu attribute 'stdcall' ignored: may affect layout/ABI (non-standard, GCC/Clang compatibility).
    • Light warning (optimization / diagnostics / informational only; ignoring changes no observable behavior): noinline, always_inline, format, unused, used, pure, const, visibility, deprecated, and the like, as well as unrecognized attribute names. Text shaped like gnu attribute 'noinline' ignored (non-standard, GCC/Clang compatibility).
  • None of these warnings block compilation or change the exit code.

The positions where __attribute__ may appear (matching GCC): before the declaration specifiers; between the struct/union keyword and its tag name and between the tag name and {; after the closing } (before a typedef/variable name) and after a typedef name; between the return type and the function name; before the type of a cast’s abstract declarator; before the * inside a function-type parenthesis.

struct __attribute__((aligned(32))) Block { char c; };   // _Alignof(Block) == 32
int  __attribute__((aligned(16))) giant;                  // raises alignment
void __attribute__((stdcall)) api(void);                  // accepted + strong warning (stdcall ignored)
int  __attribute__((noinline)) leaf(void) { return 42; }  // accepted + light warning

Compatibility note (important):

  1. Real GCC/Clang fully implement these attributes; Co currently honors aligned and packed (the latter limited to the binding positions listed above; “together with bit-fields” has also taken real effect since the V0.5.0 continuation batch) and keeps handling the rest as “syntax accepted + semantics ignored + tiered warning”. If source code relies on a particular calling convention, or on linkage attributes such as section/alias, it still compiles under Co but behaves differently from GCC/Clang — this is exactly why Co emits a strong warning for every ignored “layout/ABI” attribute instead of accepting it silently.
  2. When a real layout effect is needed, aligned can be rewritten as the C23 _Alignas(N); packed has no standard counterpart, so the GNU spelling is the only way to ask for it (Co honors its attribute-side effect). #pragma pack, meanwhile, has real layout effects as well since V0.5.0 (pack(N), pack(push, N)/pack(push)/pack(pop), pack(0) and a bare pack() reset all follow the clang semantics and are observable via sizeof/_Alignof/offsetof) — the two spellings are interchangeable; the only difference is their shape: packed is a type-level binding (written on a type or a field) while #pragma pack is an alignment cap over a lexical scope (effective from the pragma onward, restored by pop).
  3. __declspec(...) (the MSVC extension) is out of scope for this extension and not supported; use [[lib("X")]] for library ownership.
  4. The rare aligned forms (bare aligned with no argument, aligned(_Alignof(T)), aligned(type)) are downgraded to a light-warning ignore in this batch.

Current boundaries (compiler implementation status)

  • packed implementation status (since V0.5.0): the __attribute__((packed)) attribute really changes the layout (see the previous section for the binding positions and for “an explicit alignment wins”, “no recursive rewrite of nested types” and “bit-fields take real effect as well”); #pragma pack really changes the layout too, since V0.5.0 — pack(N), pack(push, N)/pack(push)/pack(pop), pack(0) and a bare pack() reset all follow the clang semantics. Four boundaries: (1) alignment cap: a member’s effective alignment is min(natural alignment, N), i.e. pack compresses only the natural alignment, never an explicitly declared one (_Alignas, type-level aligned), and pack(16) never raises alignment; (2) scope stack: push/pop restore one another, and a pop on an empty stack warns and is ignored; (3) fixed at the definition point: a record takes the cap in effect where its struct/union is defined, so a later pop does not affect an already-defined type; (4) a record with bit-fields is equally subject to pack — a bit-field’s storage unit keeps the width of its declared type (int : 4 still occupies 4 bytes), and pack only compresses the unit’s placement alignment to min(natural, N) (pack(1) is equivalent to packed); a zero-width :0 merely closes the current unit, occupies no space and contributes no alignment; a change of unit type (or an overflow) opens a new unit. Probed forms: struct { char c; int i : 4; } is 6/2 under pack(2), 8/4 under pack(4) and 5/1 when packed; struct { unsigned a : 3; unsigned b : 5; char c; } is 8/4 naturally and 5/1 when packed — all matching the local clang value for value. An invalid argument (not 1/2/4/8/16) warns and is ignored, and a quoted push, "name" is ignored as clang does. packed with bit-fields and #pragma pack(1) with bit-fields are equivalent spellings.
  • [[lib("X")]] lowers to a /DEFAULTLIB linker directive in the COFF .drectve section, deduplicated by first appearance; this relies on the link step consuming the directive and cannot yet do “precise per-symbol binding to a specific dll” — per-symbol binding for same-named symbols across multiple dlls is a later linker capability.
  • [[deprecated]] is limited to reference-site warnings on top-level functions and global variables; local declaration positions are inert, and C23’s second legal spot (after the declarator) is not modeled.
  • The first batch of [[nodiscard]] / [[noreturn]] semantics has landed (discard warnings / non-return verification). Boundaries: marking a non-function declaration (e.g. [[nodiscard]] int x = 7;) is accepted silently; marking a struct/union type or a function-pointer type (allowed by C23) is not modeled; the old [[_Noreturn]] spelling draws no deprecation warning.
  • [[maybe_unused]], [[fallthrough]], [[align]] and others remain silently accepted — Co currently has no “unused variable” or “implicit fallthrough” class warnings for them to suppress; they will be enabled when such warnings land.
  • [[subsystem("windows")]] is realized via the linker command-line -subsystem:windows, which takes precedence over the static CRT’s embedded .drectve; the entry then resolves to WinMainCRTStartup for WinMain, otherwise pinned to mainCRTStartup. It is valid only for Windows/COFF targets; the wide variant wWinMain is not yet supported.

Data Types

This chapter covers Co’s built-in types — integers, character types, booleans, floating-point types, pointers and arrays — together with _BitInt, typedef / typeof / auto, the typing of literals, qualifiers, and implicit-conversion rules. The baseline is ISO C (C23 recommended); on top of it Co carries one breaking extension: inside .co files long is always 64 bits (see “Co extension · long is 64-bit in .co”). For struct / union / enum see the “struct / union / enum” chapter, for class see the “class” chapter.

All widths below are measured on Windows x64; on Linux x64 pointers are 8 and long is 8 (native LP64 for the target), everything else is unchanged.

Syntax

type ::=  integer-type            [ qualifier … ]
       |  floating-type           [ qualifier … ]
       |  void                   [ qualifier … ]
       |  type  *                [ qualifier … ]              // pointer
       |  type  [ constant-expression ]                        // array (length may be empty → flexible member / inferred)
       |  ( struct | union | enum ) [ TAG ] { … } | TAG        // derived types, see the respective chapter
       |  typeof ( type | expression )
       |  typeof_unqual ( type | expression )
       |  auto                                                  // inferred from the initializer (C23)
       |  _BitInt ( integer-constant )

Integer specifiers may be combined freely in any order; the omitted width defaults to int:

SpellingEquivalent type
char / signed char / unsigned chardistinct types (char and signed char share width 1)
short / short int / signed short / unsigned shortshort / unsigned short
int / signed / signed int / unsignedint / unsigned int
long / long int / signed longlong
long long / long long int / unsigned long longlong long / unsigned long long
_Bool / boolthe same type (bool is the spelling Co recommends)

Qualifiers: const, volatile, restrict, _Atomic.

Widths and alignment

Type.c / .h.co
_Bool / bool1 / 11 / 1
char, signed char, unsigned char1 / 11 / 1
short, unsigned short2 / 22 / 2
int, unsigned int4 / 44 / 4
long, unsigned long4 / 48 / 8
long long, unsigned long long8 / 88 / 8
float4 / 44 / 4
double, long double8 / 88 / 8
wchar_t2 / 22 / 2
char8_t1 / 11 / 1
char16_t2 / 22 / 2
char32_t4 / 44 / 4
Any pointer, void*8 / 88 / 8
enum4 / 44 / 4
size_t, ptrdiff_t, intptr_t8 / 88 / 8
_BitInt(N)ceil(N/8) / see belowsame as left

Cells are formatted “sizeof / _Alignof”. The width of a struct / union follows from member layout and alignment; see the respective chapter.

Semantics

(This section describes the externally-observable semantics and behaviour; internal implementation mechanisms are out of scope.)

Integers

The widths of char, short, int and long long match ISO C; long is the only type whose width differs between .co and .c (see the dedicated section below). signed and unsigned used alone mean int / unsigned int.

  • char is signed (char c = -1; printf("%d", c) prints -1), matching the MSVC / clang default on Windows. Write unsigned char explicitly when you need unsigned semantics.
  • Unsigned arithmetic wraps modulo the type width: unsigned v = 0u - 1u; yields 4294967295.
  • Signed overflow remains undefined behaviour; the language makes no saturation or wrap-around promise.
  • <stdint.h> gives int8_t … int64_t / uint64_t at the widths listed above; <stddef.h> gives size_t / ptrdiff_t / nullptr_t, all 8 bytes (pointer width).

Character and boolean types

wchar_t is 2 bytes unsigned (aligned with the host CRT’s wide-character semantics, i.e. a Windows UTF-16 code unit). char8_t / char16_t / char32_t (C23 / C11) are 1 / 2 / 4 bytes and always unsigned.

bool and _Bool are the same type: 1 byte wide, false == 0, true == 1, and every assignment normalises to 0 or 1 (bool b = 5; yields 1). They are two spellings of one type and therefore must not appear as two separate associations in a _Generic.

Floating-point types

float is 4 bytes, double is 8. long double is accepted syntactically, takes part in arithmetic and can be printed with %Lf, but its width equals double (8 bytes) — extended (x87-style) precision is not provided today.

  • Floating-point types do not accept signed / unsigned (as ISO C requires): signed float, unsigned double and unsigned long double are all rejected with a diagnostic such as 'float' cannot be signed or unsigned; diagnostics spell long double as double.
  • Floating literals take only the four suffixes f / F / l / L, and upper and lower case must not be mixed (1.0lF is rejected). 1.0d is not a valid suffix.

Arbitrary-width integers _BitInt(N)

C23’s _BitInt(N) is supported for N in 1..65535:

  • sizeof(_BitInt(N)) == (N + 7) / 8.
  • _Alignof is bucketed by width: N ≤ 8 → 1, N ≤ 16 → 2, N ≤ 32 → 4, anything wider → 8 (measured: _BitInt(40) is size 5 / align 8, _BitInt(128) is 16 / 8).
  • Signed by default; unsigned _BitInt(N) may be written. Arithmetic truncates to the declared bit width (100 + 27 on _BitInt(7) yields -1).
  • Mixed with int the result is int (the integer rank of _BitInt(N) is below int).
  • For 128-bit integers write _BitInt(128); __int128 is not a spelling of this language.

Pointers and void

All object pointers are 8 bytes wide. void* converts implicitly to and from any object pointer, no cast needed (int v = 5; void *p = &v; int *q = p; passes as written). nullptr_t (<stddef.h>) and void* are two spellings of the same type, so they cannot be listed as two separate associations in a _Generic; both NULL and nullptr work for null-pointer initialisation and comparison. Function pointers may be variables, parameters and return values (int (*f)(int, int) = add; f(2, 3);).

Arrays

sizeof of int a[10]; is element width × length; multi-dimensional arrays are stored contiguously in row-major order (int m[3][4] is 48). A string literal is a character array including the trailing \0: sizeof("abc") == 4, sizeof("") == 1.

  • char b[4] = "hi"; zero-fills the remaining elements; char c[2] = "hi"; is allowed to truncate without \0.
  • Arrays degenerate to pointers as function parameters: whether written int f(int a[4]) or as a VLA parameter int f(int n, int a[n]), sizeof(a) inside the function body is 8 (pointer width), not the total element width.
  • Variable-length arrays (VLAs) are accepted syntactically, and sizeof(a) is computed from the current value of the length expression at the point where sizeof is evaluated (consistent with ISO C): after int n = 5; int a[n];, changing n to 9 makes sizeof(a) yield 36. The array object does not grow with n; accessing past the original extent once n is larger remains undefined behaviour.
  • Flexible array members (char data[];) are covered by the “struct / union / enum” chapter.

Type aliases and inference

  • typedef behaves as in ISO C and works for function pointers, arrays and structs; a typedef name participates in type-spelling reconstruction (diagnostics keep the alias form).
  • typeof(x) (C23) yields the type of an expression or a type; arrays and structs both work: typeof(a) b; declares an array of the same dimension. The result of typeof is a type name, so it can be written directly inside sizeof(typeof(e)) and _Alignof(typeof(e)). typeof_unqual(x) gives the same type with top-level qualifiers stripped.
  • auto (C23) infers from the initializer: auto x = 1; is int, auto p = &v; is a pointer, auto n = 3.5; is double, and auto f = 2.0f; keeps float (no default promotion). The form auto *p = &v;, which puts * into the declarator after auto, is not supported today — write pointers as auto p = &v;.

Types of literals

An integer literal takes the first type in the C standard candidate sequence that can hold the value; the suffix determines the candidate set.

Literal.c / .h.co
1int (4)int (4)
1uunsigned int (4)unsigned int (4)
1L / 1llong (4)long long (8)
1ULunsigned long (4)unsigned long long (8)
1LL / 1ULLlong long / unsigned long long (8)same as left
3000000000, 0xffffffff, 0x1000000008 / 4 / 8same as left
1wb / 1ubexact-width _BitInt literal (1)same as left

Key points:

  • An unsuffixed decimal that exceeds int promotes to long (in .c 4 bytes cannot hold it, so it skips to long long); hence sizeof(3000000000) == 8.
  • Octal and hexadecimal try the unsigned candidates first, hence sizeof(0xffffffff) == 4 (unsigned int).
  • In the .co dialect long and long long are both 64-bit, so after de-duplicating the candidate sequence 1L and 1UL land on 64 bits directly.
  • Floating literals default to double: 1.0, .5 and 1.0L are all 8 bytes; 1.0f / 1.0F are float.
  • The type of a character constant 'a' is int (sizeof('a') == 4); the prefixed forms are L'a' → wchar_t (2), u'a' → char16_t (2), U'a' → char32_t (4).
  • For exact-width literals the suffix must be written in full as wb / ub: sizeof(1wb) == 1, sizeof(255wb) == 2; the truncated 1w and 0x1w are rejected as invalid suffixes (invalid suffix 'w' on integer constant) rather than passing as an ordinary int. Integer suffixes likewise require consistent case pairing: 1lL and 1wB are rejected, while 1ll, 1llu, 1uwb and 1UWB are accepted.
  • The string prefixes u8"…", u"…", U"…" and L"…" have char8_t, char16_t, char32_t and wchar_t elements respectively, with width (number of code units + 1) × element width.

Qualifiers

const has real read-only semantics (writing to a const object is an error). volatile, restrict and _Atomic participate in type spelling and compatibility checking but currently do not change code generation — volatile does not inhibit optimisation nor order volatile accesses; for atomic operations call the <stdatomic.h> functions such as atomic_load / atomic_store, which do emit genuine atomic instructions. register is accepted and is a no-op.

Implicit conversions, promotions and arithmetic conversions

  • Integer promotion: narrow integer types such as char / short are promoted to int before arithmetic (int when it can hold all values, otherwise unsigned int). Hence (char)100 + (char)100 gives 200 and short a = 30000; a + a gives 60000, neither overflowing.
  • Usual arithmetic conversions: on the integer side the wider type wins, and at equal width the unsigned side dominates — unsigned + int is unsigned int, int + long long is long long; on the floating side mixing float with double yields double.
  • Explicit casts (T)e truncate the value: (char)300 gives 44, (unsigned char)-1 gives 255; float-to-integer conversion truncates toward zero: (float)3.99 gives 3, (double)-2.7 gives -2.
  • The type of an assignment expression is the type of its left operand (float f; sizeof(f = f + d) is 4).
  • Pointers and integers may be cast to each other; _Generic dispatches on the exact type, and bool / _Bool, or long / long long inside .co, cannot be listed together because they are the same type.

sizeof, _Alignof and _Alignas

  • sizeof applies to both types and expressions; applied to an arithmetic expression involving variables, the result is computed from the expression’s actual type: with double d; float f;, sizeof(d + d), sizeof(-d), sizeof(1 + d) and sizeof(d / f) all yield 8, sizeof(f + f) yields 4, and sizeof(c + c) (with char c;, after integer promotion) yields 4.
  • Applied to a struct, sizeof returns the total width including padding, and a flexible array member contributes 0; applied to a string it includes the \0.
  • sizeof(void) yields 1 and sizeof(function) yields 1 — an extension kept for compatibility with GNU sources; ISO C does not define it.
  • A compound literal may be the operand: sizeof (int){1} yields 4, sizeof (double){0} yields 8, sizeof (int[3]){0} yields 12. When the parentheses hold a type name, the width still comes from the type, so sizeof (int) - 1 is sizeof(int) - 1 (yields 3), not a compound literal.
  • _Alignof(T) with a type name matches ISO C; it also accepts the expression form (the GNU extension clang accepts as well): _Alignof d and _Alignof(d + 1) both yield the alignment of the operand’s type. Without parentheses it binds as a unary expression, so _Alignof d + 1 is (_Alignof d) + 1 (yields 9). The spellings _Alignof / __alignof__ / alignof are equivalent.
  • _Alignas(N) may be used on variables and struct members; the effective alignment is “the greater of natural alignment and N”: _Alignas(32) char buf[8]; places buf on a 32-byte boundary, and struct { char c; _Alignas(16) int i; }; has sizeof 32. __attribute__((aligned(N))) contributes with equivalent effect (see the “Attributes” chapter).

Co extension · long is 64-bit in .co

This is the only width discontinuity Co introduces relative to C, and the only breaking difference in this chapter:

  • Inside .co / .CO files, long / unsigned long are always 8 bytes (as wide as long long); in .h, .c and every other source file they stay native to the target (4 on Windows, 8 on Linux). Combined spellings widen too: long int and signed long are also 8 bytes in .co.
  • The decision is made per source file of each declaration itself, not per “whole translation unit”: when a .co file #includes a .h, the long in that header is still 4 bytes. Consequently the layout of a struct in a shared header is byte-for-byte identical on the .co and .c sides — a single header never yields two different sizeof values in the two kinds of source.
  • long and L literals produced by macro expansion follow the dialect of the use site: with #define BIG 0x100000000L in a shared header, expanding it inside a .co file computes in 64 bits and does not falsely report overflow.
  • Two writing disciplines derived from the 64-bit long in .co:
    • Always write explicit widths when calling external (C) interfaces: if the callee returns 32 bits (Win32 DWORD / LONG), write int / unsigned int; write long or long long only when it truly returns 64 bits. The language provides no “reject external declarations containing long” check — the compiler cannot see the real external signature and has no authority to judge correctness.
    • Inside .co, long and long long are the same type, so _Generic(x, long: 1, long long: 2) fails as a duplicate association; diagnostics may spell a .co long as long long.
  • Where a value must stay consistent across .co and .c, prefer int32_t / int64_t outright.

Compatibility notice (regarding long): in a .co file, printf("%ld", v) passes 8 bytes while %ld reads only 4; the language performs no format-string checking, so use %lld or a PRId64-style spelling instead. Also, #include <limits.h> inside a .co file still yields the 4-byte LONG_MAX (2147483647) — test the range of a 64-bit long against INT64_MAX. These two points are language-level discontinuities that data-model macros cannot cover, and must be carried by writing discipline.

Current boundaries (not yet supported / not finalized)

  • _Complex / _Imaginary and the 2.0i imaginary literal are not implemented (writing _Complex is diagnosed directly).
  • __int128 is not a spelling of this language; use _BitInt(128).
  • long double has no extended precision — equivalent to double.
  • The volatile / restrict / _Atomic specifiers do not reach code generation; they only affect type spelling and compatibility.
  • auto *p = &v; is not supported (the *-declarator form following auto); write auto p = &v;.
  • Bare tags as types (Point p;) are enabled only in .co; in .c you still must write struct Point p; — see the “struct / union / enum” chapter.
  • GNU statement expressions ({ ... }) are not supported (e.g. x = ({ int t = 3; t + 4; }); C has no such syntax — it is a vendor extension). Writing one produces GNU statement expression '({ ... })' is not supported, and the whole braced block is skipped, so one occurrence reports once. Rewrite it as ordinary statements or a helper function.
  • GNU range designators [a ... b] are not supported (e.g. int arr[4] = { [0 ... 2] = 7 };, t.a[1 ... 5] = 9; C has no such syntax — it is a vendor extension). Writing one produces GNU range designator '[a ... b]' is not supported; the upper-bound expression is consumed and discarded, and the following ] / = / initializer still parse normally, so one occurrence reports once. For the same fill effect, list the designators one by one (e.g. [0]=7, [1]=7, [2]=7) or assign in a loop.

Reserved names

bool, true, false, nullptr, constexpr, typeof, typeof_unqual, _BitInt, alignas, alignof, static_assert, thread_local, class, new, this, public, import, module and the like are Co keywords and cannot be used as identifiers (bool / true / false are reserved even inside .c; int bool = 1; is diagnosed directly). C++’s decltype is not a Co keyword and is not implemented — it is simply an ordinary identifier; use typeof(e) to obtain the type of an expression. The remaining spellings (int, long, float, _Bool, _Complex, _Imaginary, _Atomic, _Generic, _Noreturn, wchar_t, char8_t, char16_t, char32_t, restrict, volatile) are reserved for the implementation under the C language-layer rules, and a program may not overload their meaning.

struct / union / enum

This chapter covers the three value types in Co — struct (data aggregate), union (shared storage), and enum (named integer constants) — with their ISO C baseline plus two Co-only extensions: public cross-module visibility and bare tag as type (only in .co). For the reference type class, see the “class” chapter.

Syntax

[ public ] ( struct | union ) TAG
{
	member-declaration …
};

[ public ] enum TAG
{
	CONST [ = const-expression ] , …
};

member-declaration ::=  type  name  [ : bit-width ]  ;
	                    |  ( struct | union ) [ TAG ] { member-declaration … } ;    // anonymous member
	                    |  type  name  []  ;                                        // flexible array member (last position)

Variable and parameter declarations:

( struct | union | enum ) TAG  name [ = initializer ] ;   // keyword form (ISO C compatible, `.c` and `.co`)
TAG                         name [ = initializer ] ;      // bare-tag form (`.co` only)

Initializers: positional list { v0, v1, … }; designated initializer { .member = value , … } (may be out of order; unlisted members are zero-filled); array subscript [ index ] = value. Designators may chain downward into nested members/elements: .a[2].b, [1][2] (C11 designator sequences).

ElementMeaning
TAGTag name; usable as a type identifier within the TU (bare-tag form, .co only)
publicCross-module visibility gate; without it the type stays module-internal and cannot be import-ed
member-declarationOrder in source equals layout order (subject to ISO C alignment rules except within a bit-field run)
: bit-widthBit field; width must be an integer constant not exceeding the underlying type’s width
anonymous memberInline struct or union with no name; its members are promoted into the host
name []Flexible array member; must be the last member; sizeof excludes its length

Semantics

(This section describes the externally-observable semantics; internal implementation mechanisms are out of scope.)

Positioning

struct, union, and enum are all value types: a variable denotes a fixed region of storage, assignment copies bytes, lifetime follows scope, and there are no constructors or destructors. Contrast with class, which is a reference type stored on the heap and reclaimed automatically by Co.

Boundary with class

structclass
Kindvalue typereference type
Contentsmember variables onlyfields + methods + ctor/dtor + static members
Storagestack value / heap handleheap (class is always heap-allocated)
Reclamationfollows scopeCo automatic memory management

See the “Boundary with struct” subsection of the “class” chapter for details.

struct: definition and use

Supports named tags, forward declarations (incomplete types), self-reference via pointers, positional and designated initializers, and . / -> member access.

struct Point
{
	int x;
	int y;
};

struct Node                                // self-referential: member is a pointer to itself
{
	int          value;
	struct Node *next;
};

struct Point a = { 3, 4 };                 // positional
struct Point b = { .y = 7, .x = 3 };       // designated (may be out of order; unlisted fields zero-fill)
struct Point c;                            // uninitialized: holds whatever was on the stack
c.x = 1; c.y = 2;

struct Point *p = &a;
printf("%d %d\n", p->x, c.y);

struct Point d = c;                        // assignment is a byte-for-byte copy

union: definition and use

All members of a union share one storage region; the size of the union equals its largest member. Only one member is considered “active” at any moment — writing a member makes that member active. Maintaining this invariant is the programmer’s responsibility.

union Value
{
	int  i;
	char b[4];
};

union Value u;
u.i = 256;
printf("%d\n", u.i);           // 256
u.b[0] = 1;                    // after this write, reading i is no longer meaningful

An anonymous union placed inside a struct has its members promoted into the host — you access them via the host directly, with no intermediate name. This is the common tagged-union idiom:

struct Tagged
{
	int tag;
	union
	{
		int   i;
		float f;
	};
};

struct Tagged t;
t.tag = 1;
t.i   = 42;                    // anonymous union member promoted to host

Conversely, an anonymous struct placed inside a union has its members promoted into the host union — you access them through the union directly, while each member keeps its own offset inside that struct. This is exactly the Win32 LARGE_INTEGER shape (LowPart / HighPart / QuadPart):

union LongLong
{
	struct
	{
		int lo;
		int hi;                     // offset 4 from the anonymous struct's start
	};
	long long q;                    // overlaps the same 8 bytes as lo / hi
};

union LongLong v;
v.q = 0x0000000200000001LL;         // write all 64 bits at once
printf("%d %d\n", v.lo, v.hi);      // 1 2 (little-endian: low 32 bits in lo, high 32 bits in hi)
v.hi = 3;                           // update only the high 32 bits
printf("%lld\n", v.q);              // 0x300000001

sizeof(union LongLong) == 8; the promoted lo / hi and q are different views of the same storage. A designated initializer may target a promoted member or a non-first member directly: union LongLong g = { .hi = 3 }; and union LongLong h = { .q = 1 };.

enum: definition and use

enum defines a set of named integer constants. Its underlying type is equivalent to int (sizeof(Color) == sizeof(int)). Both named (enum TAG { … }) and anonymous (enum { … }) forms are accepted. A constant may carry an explicit integer value; a constant without an explicit value takes the previous value plus one.

enum Color { RED, GREEN, BLUE };                       // 0 / 1 / 2
enum Kind  { A = 1, B = 2, C = 10, D };                // D follows C, so 11

Color c = GREEN;
if (c == 1) { }                                        // equivalent to plain integer comparison

An anonymous enum { … }; places its constant names directly into the ordinary identifier namespace.

Bit fields

A member followed by : integer-constant declares a bit field whose width must not exceed the underlying type’s bit width. Bit fields declared back-to-back are packed into the same storage unit in declaration order; overflow starts a new unit. Anonymous bit fields (a bare : N with no name) serve as padding.

struct Basic
{
	unsigned a : 3;                        // bits 0-2
	unsigned b : 5;                        // bits 3-7
	unsigned c : 8;                        // bits 8-15
	unsigned d : 16;                       // bits 16-31
};                                         // sizeof == 4 (single i32 unit)

struct Mixed
{
	int        header;                     // regular field, 4 bytes
	unsigned   f1 : 1;
	unsigned   f2 : 7;
	int        payload;                    // 4 bytes
};

struct Basic x = {0, 0, 0, 0};
x.a = 7; x.b = 31; x.c = 200; x.d = 0xABCD;
printf("a=%d b=%d c=%d d=0x%x\n", x.a, x.b, x.c, x.d);

Bit fields can be read, written, updated via compound assignments (+=, |=, …), and accessed through pointers (p->f1 = 1;). In initializer lists, bit-field values are written into the same storage unit one by one in declaration order (mask-merged), never clobbering neighbouring fields.

Flexible array member

The last member may be declared as type name [];. sizeof on the enclosing struct does not count the flexible portion. The usual pattern is a leading length field followed by the flexible array.

struct FlexStr
{
	int  len;
	char data[];                    // header only; the payload comes from an external buffer
};

char buf[32];
struct FlexStr *fs = (struct FlexStr *)buf;
fs->len     = 2;
fs->data[0] = 'H';
fs->data[1] = 'i';
fs->data[2] = '\0';
printf("len=%d s=%s\n", fs->len, fs->data);

Value semantics and sizeof

  • Assignment / by-value parameters / returns all copy the underlying bytes; modifying the copy does not touch the original.
  • Structs may be passed and returned by value: int sum(Point a, Point b) is valid; bare-tag forms of Point also work at the call site (.co only).
  • sizeof yields the total byte size including internal padding, and includes any bytes occupied by anonymous members of the host. The flexible-array portion contributes 0.
  • sizeof may appear in a file-scope constant initializer (e.g. int sz = sizeof(Point);) — it is folded to a constant at compile time, matching the value inside a function.
  • sizeof applied to a string literal yields the array width including the trailing \0: sizeof("abc") == 4; typeof("abc") is likewise an array type.
  • Array elements, struct members, and pointer members follow ISO C semantics.

Co extension: public and cross-module

public is the only gate for cross-module type visibility. In an imported module, only struct / union / enum types marked public can be consumed by other modules; anything without public stays module-internal and is refused by import.

Module geometry.co:

public struct Point { int x; int y; };
public union  Val   { int i; char b[4]; };
public enum   Color { RED, GREEN, BLUE };
struct Secret { int raw; };                   // no public → module-internal only

Consumer main.co:

import * from "geometry.co";                  // or by name: import Point, Val from "geometry.co";

int main(void)
{
	Point        p = { .x = 1, .y = 2 };       // bare-tag form
	struct Point q = p;                         // keyword form, equivalent to the line above
	return q.x + q.y;                           // 3
}

See the “import” chapter for the two import forms, path resolution, and cycle detection.

Co extension: bare tag as type (.co only)

Inside a .co file, the tag of a struct / union / enum may be used without the leading keyword as a type — mirroring C++ style. This is part of Co’s “simplified C++” positioning (the same direction as the bool decision).

struct Point { int x; int y; };
public enum  Color { RED, GREEN, BLUE };

int sz = sizeof(Point);                     // sizeof accepts a bare tag; folded at file scope

int addp(Point a, Point b) { return a.x + b.y; }         // bare tag in parameter list

int main(void)
{
	Point   p  = { 1, 2 };                    // same as struct Point p = { 1, 2 };
	Color   c  = GREEN;                        // enum constant visible in same TU
	Point  *pp = &p;
	return p.x + c + pp->y + addp(p, p) + sz;
}
  • Same TU: any tag already defined in this file may be used bare.
  • Cross module: public struct / union / enum tags from an imported module may likewise be used bare in the consumer (see the example above).
  • Coexists with the traditional form: struct Point a; Point b; may appear side-by-side in one source file; they refer to the same type.

Compatibility note: bare-tag recognition is not enabled in .c files — Point p; still reports use of undeclared identifier 'Point' and you must write struct Point p;, exactly as in ISO C. The pure-C mode is unaffected.

Current boundaries (not yet supported / not finalized)

  • Cross-module enum constant names: a public enum’s tag may be used across modules (as a type: Color c;), but the constant names themselves (e.g. GREEN) are not currently visible across modules; consumers still write integer literals. A separate milestone covers this.
  • Inside a submodule: within an imported module, that module cannot use bare tags pulled in by its own imports. Cross-module bare-tag support applies only at the top-level main source.
  • Incomplete types, diagnosed up front: when a struct/union tag that has only a forward declaration (no body) is allocated by value — a global or local variable definition, a struct field, or an array of incomplete elements — the compiler reports an error directly (since V0.3.1, wording matching clang) instead of letting it crash in the backend. Pointer uses (declarations, parameters, p->x member access) and extern declarations remain legal with only a forward declaration.
  • Foo(3); declaration/expression ambiguity: when an identifier is simultaneously a tag and appears as the leading token of a call-statement, .co re-parses it as a declaration. This is the same class of ambiguity as existing typedef names and will be addressed later.
  • Block-scope shadowing: the granularity of shadowing a tag by an inner variable follows the existing implementation (a simplified merge of the ISO C tag namespace).

Reserved names

There are no reserved names specific to struct / union / enum. The four lifecycle-protocol reserved names of class (__new__, __retain__, __release__, __delete__) are covered in the “class” chapter.

class

Syntax

[ public ] class CLASS_NAME
{
	// constructor
	CLASS_NAME()
	{
	}

	// destructor
	~CLASS_NAME()
	{
	}

	// member variable
	[ public ] [ static ] TYPE VAR_NAME;

	// member method
	[ public ] [ static ] TYPE FUNCTION_NAME( [ TYPE VAR_NAME , ... ] )
	{
	}

	// property (a get/set accessor pair; each accessor may carry public/private, default public)
	[ public ] TYPE PROPERTY_NAME
	{
		[ public | private ] get ;   // or get { ... }   field is available in the body
		[ public | private ] set ;   // or set { ... }   value is the written value; field is available
	}
}

Description

.co source files only

class is a type form introduced by Co — C has neither this keyword nor the corresponding semantics — so class can only be defined in .co/.CO source files. A class written in .c or .h is rejected:

$ colang app.c
app.c:1:1: error: 'class' is only allowed in .co source files

What counts is the file the class keyword actually comes from: a .h pulled in by #include from a .co source gets no exemption — a class definition in that header is still rejected, and the diagnostic points at the header’s own name and line number.

(No cascade: the whole class … { … } block is skipped in one go, so one definition yields exactly one diagnostic.)

Boundary with struct

class is Co’s reference type (data + behavior), in contrast to struct (a value type, pure data, C-compatible):

structclass
Kindvalue typereference type
Contentsmember variables onlymember variables + methods + constructor/destructor + static members
Storagestack value / heap handleheap (class is only ever created on the heap)
Reclamationfollows scopemanaged automatically by Co; manual release is normally not needed
RoleC-style data aggregateencapsulation unit for OOP

Co’s object model is deliberately “simplified”: class provides encapsulation and methods but does not aim for full C++ feature coverage (see “Current boundaries”).

Creation and ownership

A class instance can only be created on the heap. After obtaining an object via new, it must be held by some variable or handed off as a return value; if nothing holds a newly created object, it becomes unreachable and leaks.

A class variable holds a reference (handle) to the object: the class name itself already denotes that reference, so you write Counter c, not Counter* (which would be a pointer-to-pointer and is not allowed in Co). Thus Counter c = new Counter(); uses c to hold the newly created heap object.

Creating and using

A minimal end-to-end example (constructor/destructor, methods, this, static with ::, and a member without public):

class Counter
{
    Counter()                { count = 0; }              // constructor
    ~Counter()               { }                         // destructor
    public void inc()        { count = count + 1; }
    public int  value()      { return this.count; }      // this refers to the current object
    public static int twice(int x) { return x * 2; }     // static member
    int count;                                           // no public -> visible only inside the class
}

Counter c = new Counter();            // created on the heap, held by c (a reference/handle)
c.inc();                              // call instance method with a dot
c.inc();
printf("%d\n", c.value());            // prints 2 (count, visible only inside the class, read via a public method)
printf("%d\n", Counter::twice(21));   // static accessed via class name + ::, prints 42
// once c leaves scope the object is reclaimed automatically; no manual release needed

Members and methods

  • Instance methods refer to the current object via the implicit this and read/write its own data.
  • static members / methods belong to the class itself rather than any instance; they exist within the module in a zero-initialized state and are accessed through the class name with the :: operator, e.g. C::m(). The static here modifies class members only; it is not the file-scope static of C (which restricts a symbol to a single translation unit). Module-internal visibility in Co is expressed by omitting public (see the “Module” chapter).
  • Accessibility: a member/method is exposed based on public — one that is not marked public (or is explicitly marked private, which is exactly equivalent at this level) is visible only inside the class; only those explicitly marked public are visible from outside. At the member/method level, public/private do not further restrict access between regions inside the class; the only place in Co that actually enforces an access restriction is the get/set accessors of a property (see the “Properties” section below).

Properties

A property looks like a field but is really a pair of accessor functions: reading it runs get, writing it runs set, and it is spelled just like an ordinary member (obj.p to read, obj.p = x to write). Properties are declared in the class body as [public] TYPE NAME { accessors … }:

class Box
{
    int _a;                              // backing field used by the explicit accessors
    Box() { _a = 0; }

    public int a {                       // both readable and writable (property is public)
        get { return _a; }               // explicit get: body refers to _a
        set { _a = value; }              // explicit set: value is the implicit parameter
    }

    public int b { get; set; }           // auto property: the compiler synthesizes a hidden field
    public int c { get; }                // read-only: only get, writing from outside errors
    public int d { set; }                // write-only: only set, reading from outside errors
    public int e { get; private set; }   // read-only to outsiders: private set, writable only inside the class
    public int score { get; set { field = value < 0 ? 0 : value; } }   // mixed: auto get, set reads/writes the synthesized backing field via field
}
  • Accessor forms: a { … } body is an explicit accessor (its body refers to a field you declared, e.g. _a); a bare ; (no body) is an auto property — the compiler synthesizes a hidden backing field, which participates in the object layout and starts at 0 (to set a custom initial value, use an explicit accessor + your own field + an assignment in the constructor instead).

  • Backing field and field: an auto property (get;/set;) gets a compiler-synthesized backing field to hold its data. As long as the property keeps at least one auto part (at least one bare get;/set;), the other accessor may be an explicit body that reads/writes that backing field directly via the contextual keyword field — e.g. public int score { get; set { field = value < 0 ? 0 : value; } }. field is a contextual keyword, not reserved: it means the backing field only inside property accessors and is an ordinary identifier elsewhere.

    • field is valid only in the accessor of an auto-implemented property; using it where both accessors give explicit bodies (no auto part = no backing) is rejected: keyword 'field' is only available in an auto-implemented property.
    • Versus a same-named member: if the class also declares a member named field, a bare field in an accessor body still means the backing field; write this.field to reach that member.
  • Read-only / write-only: giving only get makes it read-only — writing reports property '…' is read-only (no setter); giving only set makes it write-only — reading reports property '…' is write-only (no getter).

  • Compound assignment / increment-decrement: obj.p += x expands to “get, compute, set”; obj.p++ / ++obj.p / obj.p-- / --obj.p dispatch the same way (the postfix form yields the old value before the update, the prefix form the new value). Both require the property to have get and set present and each visible, otherwise a read-only / write-only / private diagnostic is reported as appropriate.

  • No address-of: a property is a pair of accessor functions with no storage address of its own, so &obj.p is rejected: cannot take address of property 'p'.

  • Per-accessor visibility (orthogonal to the property’s overall public): each accessor may be individually prefixed with public or private; the default is public. An accessor marked private can only be called from within the class that defines it (including reads/writes through other instances of the same class inside the class); using it from outside is rejected—

    • a private set: writing obj.p = x from outside reports setter of property 'p' is private, so the property looks read-only to outsiders;
    • a private get: reading obj.p from outside (including compound assignment and increment/decrement) reports getter of property 'p' is private, so the property looks write-only to outsiders.

    This differs from the rule that “private at the module/member level is just an explicit spelling of omitting public and adds no restriction”—private on a property accessor does enforce a real access restriction; it is the only place in Co’s visibility rules that carries enforcement.

  • Across modules: after importing another module’s public class, its properties and their per-accessor public/private behave the same — writing a private setter or reading a private getter from outside (including the host module) is rejected consistently.

Current boundaries: properties of handle (class-reference) type are now supported — reading (get) returns a borrowed reference, and writing (set) maintains reference counting by “retain the new value, then release the old one”, sharing safely with other owners. Taking a property’s address (&obj.p) is now rejected with a diagnostic, and increment/decrement (obj.p++ / obj.p-- and their prefix forms) is now supported.

Lifetime (observable behavior)

Co manages the memory of class objects automatically. The following rules are observable by users:

  • No manual release: when an object is no longer held by any variable and the relevant scope ends, it is reclaimed automatically.
  • No dangling, no double free: handing an object to another variable never causes the same object to be freed twice, nor does it produce a dangling reference into freed memory.
  • When destruction runs: before an object is reclaimed, its destructor runs; members are still readable at that point, so it can be used to release external resources.
  • Cycles are not guaranteed to be collected: if two objects reference each other forming a cycle, automatic reclamation of that group is not currently guaranteed; the policy is still being finalized.
  • Handing over an owned handle is safe: returning an object that is already held by a local variable or a member is legal; the compiler automatically adds one reference for it, so after the return the object is safely shared with its owner and is not released prematurely.

Compatibility note: Co’s class memory management is neither like C++ (manual RAII or explicit release) nor like garbage collection (GC does not guarantee collecting cycles). Do not carry over intuition from either.

Constructor and destructor

  • Constructor CLASS_NAME(): runs when the object is created, for initialization. It shares the class name and has no return type.
  • Destructor ~CLASS_NAME(): runs before the object is reclaimed, for releasing resources. It is prefixed with ~ and has no return type.

Current boundaries (not yet supported / being finalized)

The following are currently unsupported or still being finalized; using them yields a compiler diagnostic:

  • Inheritance, virtual functions, and polymorphism are not part of the current baseline.
  • Cycles are not guaranteed to be reclaimed automatically; to break one you can use delete to destroy explicitly.

The following are now supported (previously listed as boundaries, now open): properties of handle (class-reference) type (reading returns a borrowed reference, writing retains-new/releases-old by reference counting); member and parameter types are no longer limited to primitives — a class handle, struct / union / array can all be used as members or parameters (the value-semantics embedding, borrow-parameter, and host-ownership reference-counting rules are covered in the relevant sections); explicit delete is available; a public class brought in via import can be consumed across modules (see the “Module” chapter).

Reserved names

__new__, __retain__, __release__, and __delete__ are reserved by the language and must not be used to name variables, functions, classes, or members.

Module

As of V0.3.0, the Co module system has landed alongside import (.co source merge): one .co file is one module, public is the single gate serving both dynamic-library export and cross-module visibility, and top-level statements of imported modules run exactly once at first load in a centralized topological order. Since V0.3.2, modules are promoted to independent compilation closures (per-module isolation), module-alias qualified access m.f() / m.x is enabled, and DLL / WinMain top-level-init carriers have landed. Using .obj / .dll / .so as importable modules is still deferred to later milestones.

One file is one module

One .co source file is one module. The module is the basic unit Co uses to organize a program and draw interface boundaries: names defined inside a module belong to that module by default; to let other modules use them, mark them public explicitly.

A module is named after its file by default (the file name without the extension); on import, as can give it a local alias used for qualified access alias.f() / alias.x (enabled since V0.3.2). When the file name is not a valid identifier, the default qualifier is unusable and an explicit as alias is required. During loading, the canonical absolute path (case-insensitive on Windows) serves as the module’s unique key; a module imported from multiple sites is loaded and merged only once.

Modules exist to support organizing large projects and to avoid the duplicate-definition and synchronization costs that C/C++ header (.h/.cpp) separation brings.

The external interface: public

  • public is Co’s keyword for making something external. It serves two roles at once: marking the module interface (importable by other modules) and dynamic-library export (written to the DLL export table); there is no separate export. private may appear anywhere as an explicit spelling of omitting public — its export and cross-module meaning are identical to omitting public and add no further visibility change. The only place in Co that actually enforces an access restriction is the get/set accessors of a class property (see the “class” chapter).
  • A definition without public is visible only inside its module; only a public definition is externally visible and importable.
  • public may modify top-level functions, global variables, and struct / union / enum types (cross-module type visibility has been available since 0.3.0/0.3.1), as well as file-scope typedef (public typedef int MyInt;, part of the export surface since V0.4.1.40; a non-public typedef is not exported); public on class and its members has been available since V0.4.0; a public class from an imported module can be new-ed and its instance/static members, fields and properties used from the consuming module (cross-module consumption confirmed working since P391).
  • Non-public imported symbols are forced to InternalLinkage during codegen — references within the same module resolve, but no externally-visible LLVM value is emitted.

Same-name tags: warning + qualified type names

When two or more imported modules export a same-named public tag (struct / union / enum / class), a type reference becomes ambiguous — same-named types from different modules usually differ in layout, and binding the wrong one is a silent miscompile. Since V0.4.1 the rule has three stages:

  1. Unconditional warning on the definition side: tag 'Leaf' is exported by multiple imported modules (leaf_a.Leaf, leaf_b.Leaf); unqualified references are an error, use a qualified name. It does not care whether the layouts match, nor whether the name is actually used — same name is enough (compilation proceeds).
  2. Bare names rejected on the use side: a host bare-name reference to that tag (declaration / signature / member type / cast / sizeof / _Alignof / typeof / new / Tag::static) → reference to 'Leaf' is ambiguous ...; use a qualified name. Not an error when the host defines a same-named type itself (the local definition wins, same rule as functions/globals).
  3. Qualified type names as the escape hatch: write a.Leaf / b.Leaf (a is the as alias, or the filename stem without an alias) to bind each module’s own definition:
b.Leaf l;                 // qualified names work in type-name positions
l.y = 7;
sizeof(a.Leaf);           // 4 (a's definition)
sizeof(b.Leaf);           // 16 (b's definition)

Internally the qualified name flows as a module-identity-bearing tag key (e.g. a.Leaf), so every existing tag-keyed path — member tables, completeness checks, size/alignment, layout — hits the right definition unchanged. It is therefore not merely a diagnostic but the binding mechanism that actually removes the miscompile.

For the full syntax (including qualified enum constants p.RED, qualified class statics c.Counter::total, and qualified typedef a.MyInt — only public typedef is exported), see “Same-Name Tags” in the import chapter.

Forms of a module

Physically, a module may take different artifact forms:

FormDescriptionStatus
.coSource-file module, the most direct formImplemented since V0.3.0
.objCompiled object file (-c output)Deferred to later milestones
.dll / .soNative dynamic libraryDeferred to later milestones

Why an .obj/.dll module is not “ready to use”: import needs compile-time declaration information (function prototypes, type definitions, which names are externally visible), whereas an .obj/.dll is essentially a link-time symbol definition. For a binary artifact to become an “importable module” it must additionally carry its own interface/declaration metadata — a carrier that both the specification and the compiler will define in later milestones.

Execution model of top-level statements

Top-level statements in an imported module follow “exactly once at first load + centralized topological order”: all imported modules’ top-level statements are emitted before the main entry, arranged in DFS-postorder of the dependency closure (dependencies run before dependents). The physical position of import lines in the main source has no effect on this order. main of a non-main module is not a load hook — if a module defines main, it is treated as an ordinary function symbol and does not execute automatically. See the “import (Module Import)” chapter.

Top-level initialization carrier

Top-level code needs an entry point to actually run. Different artifact forms use different carriers (since V0.3.2):

ArtifactCarrierBehavior
Console exesynthesized maincalls each module’s initializer in topological order, then runs the main source’s top-level statements
GUI exe (WinMain entry)synthesized WinMain wrapperthe user’s WinMain is renamed __co_WinMain__; the synthesized WinMain runs top-level init/statements first, then forwards (top-level code and WinMain are no longer mutually exclusive)
DLL (-o *.dll)synthesized DllMainruns top-level initialization under DLL_PROCESS_ATTACH and returns TRUE for other reasons; a user-authored DllMain is renamed __co_DllMain__ and forwarded

So a .co dynamic library still initializes when it is loaded, even if it has only a runtime-initialized global and no top-level statements — a dependent host need not call any explicit “init” function.

File-scope static alongside “omit public”

Since V0.3.0:

  • public controls cross-module visibility — omitting it means “module-internal”, adding it makes a symbol importable;
  • static keeps its C meaning — internal linkage within its own translation unit, orthogonal to public (static public / public static in either order are legal; the symbol is still internal to the TU despite the export mark);
  • In the target specification, static is only a class static-member modifier (landed since V0.4.0 class).

Not yet finalized

Deferred to later milestones:

  • The declaration-metadata carrier that lets .obj / .dll / .so become importable modules (note: producing a DLL and consuming a DLL-as-module are two different things — the former landed with the V0.3.2 carriers);
  • User-authored __init__ customization.

Currently implemented boundary (V0.4.1)

  • Module boundary: one .co file = one module; module key = canonical absolute path; same-name files in different directories are distinguished by their paths.
  • Independent compilation closures (since V0.3.2): each module builds its own type/symbol tables and is analyzed on its own before merging; same-name different-layout struct types never hijack each other; #include-brought environment symbols do not enter the export surface (ambient cut-off).
  • public: usable on top-level functions and global variables; when the artifact is a dynamic library the symbol is written into the export table (DLLExportStorageClass). In this batch public does not change linkage (non-public symbols remain ExternalLinkage by default, but non-public imported symbols are stripped to InternalLinkage by codegen).
  • static public in either order is legal; semantics match P211.
  • Dynamic-library artifacts: there is no -shared option, but the compiler switches between DLL and exe link modes automatically from the -o output extension. Naming the output *.dll produces an export-table-bearing dynamic library (an import library *.lib is generated alongside, verified on Windows).
  • Multi-file programs: compose several .co sources with import (available since V0.3.0). The single .obj from -c is useful for inspecting the compile result; linking several object files directly into an executable is still under development (see the Command Line chapter).
  • Top-level execution model: see the “import (Module Import)” chapter; this batch covers only .co consumption.
  • Cross-module type references: a public struct / union / enum imported from a module is usable as a value type (member access, address-of for passing, and sizeof all work); the consumer may also use the tag with the keyword omitted (Point p;, since V0.3.1). Main source and imported modules behave identically (since V0.4.1): instantiating a directly imported type by value inside a submodule works too, where previously only pointers and file-scope fields were supported.
  • Same-name tag adjudication (since V0.4.1): two or more modules exporting a same-named public tag → an unconditional warning on the definition side; a host bare-name reference is an error (switch to the qualified type name mod.Tag); qualified type names work in declarations, the struct keyword form, casts, sizeof/_Alignof/typeof, and new, with struct/union/enum/class handled alike. The old behaviour (later import wins; the other layout’s fields folded onto slot 0) is retired.
  • Cross-module compile-time constants: a public const int from an imported module is usable in the consumer as a read-only value, an array dimension, or a switch case label (since V0.3.1; the WM_* series in winapi.co is exactly this use).

import (Module Import)

As of V0.3.0, import is implemented for consuming .co source-file modules. Using .obj / .dll / .so as importable modules is deferred to later milestones.

Two hard limits — statement location and target: ① the import statement itself may only be written in .co/.CO source files; in .c or any other source file it is an error (see “Who may write import”); ② the import target may only be a .co/.CO module — .c/.h are permanently rejected and .bc is planned but not implemented (see “Import Target Suffix Whitelist”).

Purpose

import brings names in from other .co source files, to organize large projects and delineate interface boundaries — avoiding the duplicate-definition and synchronization costs that C/C++ header separation brings.

Syntax

Two mutually exclusive forms:

import name [as alias], … from ("file" | module_name) [as ModAlias];
import * from ("file" | module_name) [as ModAlias];
ElementMeaning
nameA specific symbol to import (must be marked public in the source module)
name as aliasA local alias for the imported name
…, …Additional name [as alias] items separated by commas
*Import every public name from the source module
"file"String-literal form; supports relative paths / cross-directory / special characters
module_nameSimplified identifier (no quotes, no extension, no separators); resolved only in the same directory
ModAliasA local alias for the source module, used for qualified access ModAlias.f() / ModAlias.x (implemented since V0.3.2); when omitted, the module’s filename stem is the default qualifier

Filename and Path Resolution

  • Two forms — pick either "file" or module_name:
    • String literal: allows cross-directory (relative or absolute) paths; the extension may be omitted (.co is auto-appended when missing).
    • Simplified identifier: equivalent to from "<name>.co", resolved in the importer’s directory.
  • Base directory: relative paths are resolved against the directory containing the importing file, not the current working directory.

Who may write import: .co source files only

import is Co-surface syntax and may appear only in .co/.CO source files:

  • import in a .c file: compile-time error 'import' is only allowed in .co source files — it is neither silently accepted nor downgraded to “recognized but not loaded”.
  • The check follows the file the statement actually appears in: if a header #included by a .co contains import, that is an error too, and the diagnostic points at the line and column inside that header — a .h is always a C-surface file, never relaxed because a .co includes it.
  • A pure C translation unit (.c) has only #include for reaching declarations across files, and a .c cannot consume any .co module (including winapi.co).

Import Target Suffix Whitelist

The import target may only be .co/.CO:

Target spellingStatusDiagnostic / behavior
"mod.co" / "mod.CO"✅ usable—
"mod" (no suffix)✅ .co appended automatically—
"mod.bc"⏳ planned, not implemented.bc modules are planned but not implemented yet
"mod.dll" / ".lib" / ".so"⏳ slot reserved for link-time consumptionbinary library import (.dll/.lib/.so) is not supported yet
"mod.c" / "mod.h"❌ permanently rejectedmust be a .co/.bc module; C source files and headers cannot be imported (use #include)
other suffixes (e.g. .txt, .obj)❌ rejectedmust be a .co/.bc module (unsupported extension '…')

The two target classes differ in nature and must not be conflated: .co is source merging (it supplies types, prototypes and definitions), whereas a future .bc / .dll / .lib / .so is link-time consumption (symbols only, no compile-time declarations, hence unable to stand in for a declaration source). The whitelist applies equally to the main source and every imported module — submodules get no exemption.

Independent Module Closures

Since V0.3.2, every .co module is an independent compilation closure: each module builds its own type and symbol tables and is analyzed on its own; the main source sees a module only through its export surface (its public names). This yields three user-visible guarantees:

  • Same-name, different-layout types never interfere: two modules may each define a struct Config with a different layout, and each sizeof uses its own layout — there is no “last importer wins” hijack.
  • Ambient cut-off: ambient symbols brought in by a module’s #include (e.g. <stdio.h>’s printf) do not enter the module’s export surface. A host that also #include <stdio.h> has its printf unconflicted with the module’s — no more “import non-public symbol” error.
  • Macros are never exported (either direction): #define is preprocessing-time text substitution and applies only to the file that defines it — it does not enter a module’s export surface, and it is not injected into an imported module either. A host macro used inside an imported module, or a module macro used in the host, reports use of undeclared identifier. Function-like macros are more insidious: a call form such as XM_ADD(2, 3) is let through at compile time by the deliberately retained C89 implicit function declaration and only fails at link time with undefined symbol: XM_ADD (object-like XM_MACRO is rejected at compile time).

The only way to share a macro is to have every consuming file #include the same header (a .h is C-surface for .co and is expanded per file); for an integer constant that must cross modules, use public const instead (both the bare name and mod.K work — see “Main Source and Submodules Alike” below).

// shared.h -- the only way to share a macro: each side includes it
#define XV_LIMIT 9

// mod.co
#include "shared.h"
public int limit(void) { return XV_LIMIT; }     // 9

// main.co
#include "shared.h"
import * from mod;
int arr[XV_LIMIT];                              // 9; XV_LIMIT cannot be imported from mod

Visibility Rules

  • public is the sole cross-module visibility gate: definitions without public are module-internal and cannot be reached by any import.
  • Named-import of a non-public symbol: compile-time error cannot import non-public symbol.
  • Non-public symbols in a module reached via import *: silently skipped — only the public surface is imported.
  • Qualified access ModAlias.x hitting a missing or non-public name in the module: error no public symbol 'x' in module 'ModAlias'; if that name is a type in the module (a non-public struct/enum/class), the diagnostic uses type wording instead: no public type 'X' in module 'ModAlias'.
  • Referring (from the main source) to a module symbol that exists but is neither named-imported nor reached via a qualifier: compile-time error identifier not imported.
  • A module referring to its own non-public symbols: allowed, unrestricted.

Main Source and Submodules Alike: Where Imported Types/Constants Are Usable

Since V0.4.1, imported public struct/union/enum types and public const values are usable in exactly the same ways in the main source and in any imported module — the module’s depth in the import graph does not matter:

  • By value: declaring local variables, function parameters/return types, struct fields, taking addresses, member access, sizeof;
  • Bare tags: omitting the struct/union/enum keyword and writing Leaf l; directly;
  • Compile-time constants: as array dimensions and switch case labels.

That is, if mid.co does import * from leaf;, then inside mid.co you may instantiate Leaf l; by value and access its members just like in the main source. This did not hold before V0.4.1 — tag/constant seeds from imported modules were injected only into the main source, so by-value instantiation inside a submodule degraded to an incomplete type (IR verification: Cannot allocate unsized type, and a member access crashed the process); only pointer and file-scope field positions worked. The restriction is removed in V0.4.1 (each submodule is loaded with seeds drawn from its own direct dependencies, through the same pipeline as the main source).

// leaf.co
public struct Leaf { int a; int b; };

// mid.co — a submodule that uses the imported type by value
import * from leaf;

public int leaf_sum(void)
{
    Leaf l;            // direct instantiation (failed before 0.4.1)
    l.a = 1;
    l.b = 2;
    return l.a + l.b;
}

Same-name tags no longer hijack silently (since V0.4.1): when one file imports two modules that both export public a same-named tag, the compiler emits a warning; if the host then refers to that tag by its bare name it is an error, requiring a qualified name (a.Leaf / b.Leaf). See “Same-Name Tags: Warning + Qualified Type Names” below.

Same-Name Tags: Warning + Qualified Type Names

Type names share the cross-module same-name problem with functions/globals, but a type also carries a layout — binding the wrong one is a silent miscompile. Since V0.4.1 this is handled in three stages: warn on the definition side, reject bare names on the use side, and provide qualified names as the escape hatch.

① Definition side (unconditional warning): as soon as two or more imported modules export a same-named public tag (struct / union / enum / class alike), compiling the host emits one warning listing every candidate:

leaf_a.co:1:22: warning: tag 'Leaf' is exported by multiple imported modules (leaf_a.Leaf, leaf_b.Leaf);
              unqualified references are an error, use a qualified name

The warning does not care whether the layouts match, nor whether the host actually uses the bare name — same name is enough. It is informational and does not affect compilation or linking. Candidates are listed as names you can actually write: the as ModAlias name when given, otherwise the filename (so example ① below, imported without an alias, reports leaf_a.Leaf, while example ② with a/b reports a.Leaf).

② Use side (bare name is an error): if the host (main source) refers to that tag by its bare name, it is an error naming the candidate qualifiers:

main.co:3:23: error: reference to 'Leaf' is ambiguous (defined in multiple imported modules:
               a.Leaf, b.Leaf); use a qualified name

It covers all type reference sites: local/global declarations, function signatures, member types, casts (Leaf)x, sizeof(Leaf) / _Alignof(Leaf), typeof(Leaf), new Leaf(), Leaf::static. Two cases are not errors:

  • the host defines a same-named type itself → the host wins (same rule as local shadowing for functions/globals);
  • only one module exports that tag → the bare name keeps working, no qualifier needed.

③ Qualified type names mod.Tag: mod is the as ModAlias name, or the filename without extension when no alias is given. Accepted in every type-name position:

import * from leaf_a as a;      // public struct Leaf { int a; };
import * from leaf_b as b;      // public struct Leaf { char *s; int y; };

b.Leaf l;                       // declaration: uses leaf_b's 16-byte layout
l.s = nullptr;
l.y = 7;
if (sizeof(a.Leaf) != 4) return 1;   // sizeof: each binds its own layout
if (sizeof(b.Leaf) != 16) return 2;
a.Leaf* p = (a.Leaf*)0;              // pointer / cast

The keyword form struct a.Leaf l; works too, and union / enum / class are structurally identical (a.Slot / a.Color / new a.Box()). Bare references inside a module (including an imported module itself) are unaffected — a bare name inside a module always binds that module’s own definition.

④ Qualified enum constants mod.RED: after functions/globals, mod.X also consults the imported module’s public enum constant table; a hit folds to an integer constant of the same value (same semantics as the bare RED, zero runtime cost):

// palette.co
public enum Color { RED, GREEN = 5, BLUE };

// main.co
import * from palette as p;

if (p.RED != 0) return 1;        // 0
if (p.BLUE != 6) return 2;       // GREEN = 5 -> BLUE = 6

Since V0.4.1.47, compile-time constant positions recognise the qualified form as well: case p.GREEN:, int arr[p.BLUE];, enum { E = p.GREEN }; and int g = p.GREEN; (including file-scope and static initializers) all fold to the same integer constant.

Still not available: bare enumeration constants do not cross modules (writing GREEN in main.co after the import still reports use of undeclared identifier) — for a cross-module integer constant use public const (see “Cross-module compile-time constants”).

④-add File-scope initializers must be constant expressions (rejected since V0.4.1.48): using a global that is neither public const nor an enumeration constant as a file-scope initializer — whether a plain int in the same file or a cross-module public int — no longer “compiles with a value of 0”; it is now a hard compile-time error whose wording matches clang -std=c23 verbatim, pointing at the referenced variable:

// main.co
import * from cfg as p;      // public int M = 5;  public const int K = 7;  public enum Size { DIM, WIDE };

int g = p.M;                 // since 0.4.1.48: error: initializer element is not a compile-time constant
int h = M;                   // the bare name (brought in by `import *`) is rejected too; so is a plain `int M` written in the same file
int ok = p.K;                // const global: folds to the real value (since 0.4.1.46)
int e = p.DIM;               // qualified enum constant: folds (since 0.4.1.47)
int *q = &p.M;               // address-of: an address constant, unaffected

Compound forms are rejected the same way (M + 1, -M, (int)M, double d = M), and the qualified compound forms are rejected as well (-p.M, (int)p.M, double d = p.M, p.M + 1 each produce one diagnostic). Four points must be known:

  • Plain C files (.c) are covered too — the C standard already requires a static-storage-duration initializer to be a constant expression; this only turns the silent fold-to-0 into a rejection;
  • No error when a runtime init carrier exists: if the .co has top-level statements (or a *.dll / WinMain carrier is produced), an unfoldable initializer is stored at runtime by the synthesized carrier, so the same line of code is judged differently in the two shapes;
  • Address-constant forms are unaffected: &p.M, array/function name decay (int *gp = arr;, int (*fp)(int) = add6;) and sizeof do not constitute a load, and are still accepted; address-constant arithmetic folds to a real address since V0.4.1.49 — arr + 1, 1 + arr, arr - 1, &x + 1, &arr[0] + 2, &arr + 1, chained arr + 1 + 1 and the string-literal base "abc" + 1 all step by the element size (arr + 1 advances by sizeof(element); &arr + 1 advances by the whole array size) — this family used to compile yet fold to null, crashing on the first runtime dereference;
  • Pointer targets are covered too (since V0.4.1.49): in int *o = &M; int *p = o; the o is a loaded non-const global, clang -std=c23 rejects it, and colang now rejects it instead of silently folding to a null pointer (the compound form o + 1, whose base is a load, is rejected as well). Since V0.4.1.50 the rejection surface extends to three further families: non-constant initializers in aggregate member positions (int a[2] = {M, 1};, {[0]=M}, {{M}, 1}, {.in.x = M}), dereference and subscript forms (*(&M), *o, *arr, *(arr + 1), arr[0], *(&s.a)), and member access (oo.y, oo.in.x, op->in.x) — each reported on the same line as clang with verbatim wording. Since V0.4.1.52 the family of explicit pointer-to-integer conversions is rejected as well: (long)(arr + 1), (long)arr, (long)&M, (int)&M, (long)(&arr[1]), (int)(long)arr, (long)add9, (long)&K and {(long)arr, 1} in an aggregate member position now error on the same line (in C a pointer-to-integer conversion is never a constant expression, so clang rejects every one of them), while a same-object pointer difference without a cast (arr - arr) and (long)(arr - arr) (whose operand is already an integer) stay accepted. Known gaps still open: a loaded extern declaration used as an initializer, and a block-scope static int s = M;. Since V0.4.1.53 array decay through a member folds to a real address: oo.buf, oo.buf + 2, oa[1].buf, the union member uu.c and {oo.buf, oa[1].buf} in an aggregate member position no longer fold to null; the same batch cures three forms that had been rejected in error (colang was stricter than clang, which reports nothing for them) — int *q = oo.m[1];, int *q = oo.m[0] + 2; and int *q = g2[1] + 1; (the subscript form of a member array and the row-decay form of a two-dimensional array), which clang now accepts identically and which fold to real addresses; the step is the width of the decayed element (oo.buf + 2 steps 1, oo.m[0] + 2 steps 4). A chain that still contains one load (the arrow op->buf, the dereference (*op).buf, or a subscript on a pointer) is not a constant address — since V0.4.1.57 such forms are rejected line for line with clang, whether the address is taken (&op->buf[1], &(*op).buf[1], &(op->m[1][2])) or the value merely decays ((*op).buf); before that version colang accepted them and folded a wrong address, treating the pointer variable’s own storage as the object base. Taking the address of the pointer variable itself (&op) is still a valid address constant and remains accepted. Since V0.4.1.55 the two remaining folding gaps are closed: a same-object pointer difference now folds to the real element count, computed as byte distance from the same root global ÷ effective pointee width — long d = &arr[1] - &arr[0]; yields 1, long d = &arr[0] - &arr[2]; yields -2, &s.b - &s.a yields the member gap — and the same batch cures int d8 = g2[1] - g2[0];, which had been rejected in error before that version; the step after a cast is now taken from the cast pointee rather than the element width of the base array — (char *)arr + 1 steps 1 byte, (short *)arr + 3 steps 2, (void *)arr + 1 steps 1 (GNU semantics, matching clang). Since V0.4.1.58 the cross-object under-report is closed: a pointer difference whose two operands resolve to distinct root globals (other - arr, &oo.in.x - &arr[0], &other[1] - &arr[1], &M - &N, ex - arr, arr + 1 - other, and { other - arr, 0 } in an aggregate member position), which colang previously accepted while silently yielding 0, is now rejected on the same line as clang (the rejection shares the folding criterion: both sides resolve to a root global, the roots differ, and the step widths are equal and positive); only a difference within the same object is a valid form and still folds to a real value. A pointer difference between incompatible pointee types is now rejected as well (since V0.4.1.62): sa - arr, (short *)arr - arr, (long *)arr - (int *)arr, (long *)&s.a - (int *)&s.a, int (*)[3] - int (*)[4], enum E1 * - enum E2 * — previously accepted and silently yielding 0 — now produce the sema diagnostic 'short *' and 'int *' are not pointers to compatible types on the same line and the same column as clang, anchored at the - operator, both for file-scope initializers and inside function bodies. Compatible forms are still accepted and never falsely rejected: int * ↔ const int * (qualification differences), enum * ↔ int *, the same type in different objects, and array names after decay. Two more items landed in the same batch: a difference between two void * operands used to crash the compiler (0xC0000005) and is now fixed, yielding a value with GNU’s byte-sized step (vp - vp2 gives -12; note that void * ↔ object pointer remains an incompatible pair and is rejected as clang does); and pointer spellings in diagnostics now match clang (int (*)[4] instead of int[4] *, int ** instead of int * *, unsigned char * instead of char *). Since V0.4.1.63 the &function fallback is closed: &function now resolves to the real function prototype (&f gives int (*)(void)), and the diagnostics align with clang accordingly — the difference form long d = &f - arr; moved from “same line and column, wrong text” to the same line, column and text; a difference between differently prototyped function names (&f - &g, i.e. int (*)(void) ↔ int (*)(int)), which used to go completely unreported because both sides degraded to void * and were then judged compatible, is now reported; and the assignment form (int (*p)(void) = &g;), previously skipped silently because one side was void *, now errors with wording verbatim identical to clang (clang anchors at the declarator name and colang at the initializer — a column difference within the established tolerance). The same batch cures a compiler crash: the legal C form (*&f)() (calling through a dereferenced function pointer), which used to crash colang at compile time, now compiles and runs exactly as clang does. Since V0.4.1.67 the bare-function-name decay form is closed: a function name that fails variable lookup now takes the real function prototype (the non-decayed function type), and the decay is left to the existing lvalue conversion — the assignment forms (int (*q)(void) = f;, int *ip = f;) and the difference forms (f - g, f - arr) now match clang line for line and verbatim (the former prints the non-decayed function type, the latter the decayed function pointers; a column difference stays within the established tolerance); sizeof(function) follows the GNU extension and equals clang’s 1 (the file-scope initializer folding order was fixed in the same batch); C23 auto pf = f; / auto pa = arr; derive a function pointer / element pointer via the lvalue conversion, and the same batch cures the regression that falsely rejected auto p = &f; (legal C is no longer an error). Since V0.4.1.73 implicit pointer ↔ integer conversions are no longer silent: initializers (long z = arr;, long z = &sobj;, long z = arr + 1;, long z = str;, long z = 1 + arr;), assignment forms (z = arr;), argument forms and block-scope declarations are all covered and match clang line for line and verbatim — initializer incompatible pointer to integer conversion initializing 'long' with an expression of type 'int[4]' (the right side still prints the non-decayed array type, anchored at the declarator name), assignment assigning to 'long' from 'int[4]' (anchored at =), argument passing 'int[4]' to parameter of type 'long' (source first); the reverse direction reports incompatible integer to pointer conversion … (e.g. int *q = 1;). Still accepted and never reported: bool targets (bool b = arr;, where clang only warns with -Wpointer-bool-conversion) and null pointer constants (int *p = 0;, int *p = 1 - 1;, (void *)0 — integer constant expressions equal to 0), plus integer sources whose value cannot be computed (int *p = x; remains under-reported). Four known gaps remain: char * ↔ signed char * is not reported (the two are indistinguishable in the type representation); a pointer-to-floating conversion prints a different wording (float f1 = arr; yields initializing 'float' with an expression of incompatible type 'int[4]', still accepted by colang); an aggregate initializer element position (int (*tbl[2])(void) = { f, g };) and a ?: conditional used as an array dimension (int a[1 == 1 ? 3 : 5];) are still not reported; and note that the value side of bool b = pointer; is implemented as a truncation (a non-zero test is unreliable). Since V0.4.1.75 a subscript base is only an array or a pointer to an object: f[1] (function designator), int (*fp)(void); fp[1], int (*tbl[2])(void); tbl[0][0], file-scope initializers (int v = f[1];) and aggregate element positions ({ f[1], 0 }) now match clang line for line — subscript of pointer to function type 'int (void)' (spelled from the prototype, anchored at the base); a function pointer base was previously silently accepted (it read function-body bytes at run time; observed crash 0xC0000005) and is rejected as well. Since V0.4.1.76 arithmetic and subscripting on a void * follow GNU semantics with a 1-byte step: the statement form void *vp; vp[1]; no longer crashes colang at compile time (it used to give 0xC0000005; clang only warns with -Wunused-value), vp + 1 / 1 + vp / vp - 1 / vp++ / vp += 1 are no longer falsely rejected with GEP into unsized type (a 1-byte step, the same rule as (void *)arr + 1 and void * - void *), and sizeof(void) / sizeof(vp[1]) are 1; reading a void element loads no memory (a zero placeholder is produced), so a null vp is safe. Since V0.4.1.77 a scalar base matches clang line for line and verbatim: int x; x[1], double d; d[1], struct S s; s[1], union U u; u[0], enum E e; e[0], 1[0], a[0][0] (anchored at the second [), x[1][2] (the first [), s.a[0], (s.a)[0], g()[0] and vf()[0] all report subscripted value is not an array, pointer, or vector, anchored at the [ of the offending level (it used to print our own wording anchored at the leftmost start of the whole base, 1–4 columns earlier). Since V0.4.1.79 a subscript on a pointer to an incomplete record is rejected by sema on the same line and with the same wording as clang — subscript of pointer to incomplete type 'struct I', anchored at the [ of that level (a forward-declared enum stays accepted, as clang accepts it; the initializer, argument, address-of, arithmetic and member-access shells all report this single diagnostic — previously the form never reached sema, was only caught in codegen as GEP into unsized type, and the enclosing shell reported an unrelated diagnostic first). Since V0.4.1.84, using a void value in binary operations, simple/compound assignments, initializers, arguments or ++/-- (e.g. vp[1] != 0, vp[1] = vp, int x = vp[1];, int y = f(); where f returns void) is rejected by sema, with this batch’s primary errors matching clang in line, wording and column, instead of silent acceptance, compiler crashes or verifier fallbacks. Binary/assignment/increment/decrement errors are anchored at the operator; void-source initializers at the declarator identifier, including function pointers, multiple declarators and multiline initializers; other compatibility families retain their existing locations. Explicit discards, void calls used as statements and void left operands of comma expressions stay accepted. In a void function, return vp[1]; / return (void)0; / return f(); are accepted under clang’s default extension policy, preserving the returned expression’s side effects (not a claim of strict ISO C validity). Returning a non-void value from a void function still errors, now including the function name. Unary operations such as -/!, condition positions and returning void to a non-void result type remain separate known gaps. Since V0.4.1.80 applying sizeof / _Alignof to an incomplete record (struct I *ip; sizeof(*ip), sizeof *ip, sizeof(struct I), _Alignof(struct I), plus typedef and union forms) also enters the sema rejection surface, matching clang line, wording and column: the type form is anchored at the sizeof keyword, the expression form at the first token after the keyword (the ( of a parenthesized form, the first operand token of the unparenthesized one); the wording is invalid application of 'sizeof' to an incomplete type 'struct I' (_Alignof prints alignof even when spelled _Alignof; typedef forms carry the (aka 'struct I') alias). A forward-declared enum (sizeof(*ep)) is still accepted, and operands already caught by an earlier diagnostic (ip->a, ip[0]) do not get this extra line; before this the family silently evaluated to 0 (mis-accepted plus a silently wrong value). Two known under-reports remain: a record defined after the sizeof (completeness means “some definition exists in the TU”) and the dimension position int arr[sizeof(*ip)];. Since V0.4.1.82 pointer arithmetic on an incomplete record (ip + 1, 1 + ip, ip - 1, ip++, --ip, ip += 1, ip -= 1, including the file-scope initializer struct I *gq = gp + 1;) is on the sema rejection surface as well, matching clang line, wording and column: the wording is arithmetic on a pointer to an incomplete type 'struct I', binary forms are anchored at the operator column while postfix/prefix ++/-- and +=/-= are anchored at the operator start, unions print 'union U' and typedefs carry (aka 'struct I'); after the error the result type is treated as unknown, so int x = ip + 1; / char *cp = ip + 1; report this single line (previously the int-conversion / incompatible-pointer line fired first), and when both sides are pointers of incompatible types only 'X *' and 'Y *' are not pointers to compatible types is reported. Two known gaps remain: 1 - ip belongs to the separate invalid operands to binary expression family (still backed by the codegen GEP into unsized type fallback), and file-scope globals whose record is defined after the arithmetic (same TU-wide rule).

For a constant use public const / public enum; to read a runtime value, assign inside a function body.

⑤ Qualified class statics mod.Counter::total: mod.Counter on the left of :: is first merged into a qualified class name, then resolved in class scope (static data members / static methods); reads, writes and calls have the same rights as with the bare class name:

import * from counter as c;      // public class Counter { public static int total; public static int twice(int x); };

if (c.Counter::twice(21) != 42) return 1;
c.Counter::total = 10;                // write: the static is one symbol across modules (linkInModule merge)
if (c.Counter::total != 10) return 2;

Name checking: c.Counter::nope -> no member named 'nope' in 'c.Counter'; c.Counter::n (a non-static member) -> invalid use of non-static data member 'n'; a misspelled module / non-public class -> no public type 'X' in module 'c'.

⑥ Qualified typedef: only public typedef is exported (since V0.4.1.40): a file-scope typedef marked public joins the export surface, so the consumer may write a.MyInt. The bare name works too (same rights as tags); when several modules export the same name, the three-stage scheme above applies — definition-side warning + bare-name error + qualified name available:

// types.co
public typedef int MyInt;
public struct Point { int x; int y; };
public typedef struct Point MyPoint;   // struct alias: the consumer gets types' layout
typedef int Hidden;                    // not public -> not exported

// main.co
import * from types as t;

t.MyInt a = 3;      // qualified name
MyInt b = 4;        // bare name (single source) works too
t.MyPoint p;        // struct alias -> types' two-member layout (even if the host has its own struct Point)
p.x = 1;
p.y = 2;
  • Only public typedef is exported: writing t.Hidden for a non-public one reports no public type 'Hidden' in module 't'.
  • Fully on par with qualified type names: declarations, parameters, return types, pointers/arrays, sizeof, casts (t.MyInt)x and initializer expressions are all accepted.
  • The underlying type must not be an imported type: public typedef a.Point Bad; (aliasing a type exported by another module) reports public typedef 'Bad' cannot alias imported type 'a.Point' — rejected deliberately in this first version, so one module’s dependency is not half-carried into another module’s export surface.
  • A host-side same-named typedef wins (the bare name binds to the host), while t.X still refers to the module’s copy — same as tags.

Breaking change (with a migration example): before V0.4.1 the same scenarios were a silent miscompile (the later import won; fields of the other layout were folded onto slot 0, so reads and writes crossed over). Code that relied on that “happens to compile” behaviour now gets an error and must switch to qualified names (a.Leaf / b.Leaf) or to distinct tag names.

The two same-named definitions (different layouts):

// leaf_a.co
public struct Leaf { int a; };              // 4 bytes

// leaf_b.co
public struct Leaf { char *s; int y; };     // 16 bytes

Before the migration (V0.4.0 and earlier: compiles, but silently miscompiles)

import * from "leaf_a.co" as a;
import * from "leaf_b.co" as b;

Leaf g;                            // cc=0, zero diagnostics: the bare name binds just one of them (the later import wins)
if (sizeof(Leaf) != 4) return 1;   // this yields 16 — nothing at compile time, it surfaces only at run time

After the migration (V0.4.1: stopped at compile time)

leaf_a.co:1:22: warning: tag 'Leaf' is exported by multiple imported modules (a.Leaf, b.Leaf);
              unqualified references are an error, use a qualified name
main.co:4:1: error: reference to 'Leaf' is ambiguous (defined in multiple imported modules:
              a.Leaf, b.Leaf); use a qualified name

Two ways to fix it

// Fix ① (recommended): qualify with the candidates the diagnostic listed, each binds its own layout
a.Leaf g;          // 4 bytes: back to the original intent
b.Leaf h;          // 16 bytes
if (sizeof(a.Leaf) != 4) return 1;
if (sizeof(b.Leaf) != 16) return 2;

Fix ②: if the two same-named types were never meant to coexist, rename the tags (e.g. LeafA / LeafB); the bare name keeps working and no qualifier is needed.

Module-Alias Qualified Access m.f() / m.x

After importing a module you can reach its public members directly with m.name, without naming each one in an import:

  • Default qualifier = the module filename without extension (importing counter.co → counter.bump(3) / counter.total).
    • If the filename is not a valid identifier (contains -, ., …), you must give an explicit alias with as ModAlias.
  • Alias override: import * from "counter.co" as CNT; → CNT.bump(3) / CNT.total.
  • What you can reach: m.f(...) (call), m.f (function reference), m.x (global read), m.x = v (global write).
  • Write parity with locals: m.x = v behaves like assigning a local variable; the only exception is writing a const global (m.constGlobal = v), rejected with read-only variable is not assignable.
  • Qualified access only reaches public members; non-public always errors no public symbol.
import * from "counter.co" as CNT;   // counter.co: public int total; public int bump(int n){...}
CNT.total = 5;                        // qualified write to a global
int a = CNT.bump(3);                  // qualified call → a == 8
return CNT.total == 8 && a == 8 ? 0 : 1;

Name-Clash Adjudication

When multiple modules export the same name to the main source, the following rules apply (m = qualifier/alias; bare name = an unqualified reference):

  1. Explicit named import vs a local of the same name → error (two explicit sources for one bare name).
  2. import * wildcard vs a local of the same name → the bare name belongs to the local; the wildcard entry is shadowed (a shadow warning is emitted). The wildcard carries only the public surface; non-public is silently excluded.
  3. Two wildcard modules share a name → the bare name is ambiguous and disabled (a reference reports identifier not imported-style), but m1.name / m2.name are each accessible via their qualifier and bind to their own definition.
  4. Default qualifier = filename stem, overridable by as ModAlias; a stem that is not a valid identifier requires an explicit alias.
  5. Two explicit named imports of the same name from different modules → error.
  6. Minimal export surface: a module’s public acts as a visibility gate when merged into the host; for exe outputs it is not individually placed in a DLL export table.
  7. Functions and globals follow the same rules: m.f and m.x share the resolution / shadowing / ambiguity trio.
  8. Qualified write parity: there is no “cross-module read-only” gate; m.x = v matches a local write (only const global writes are intercepted, see above).
  9. Type tags (struct/union/enum/class) follow the same scheme: two or more modules exporting a same-named public tag → an unconditional warning on the definition side; a host bare-name reference → reference to 'X' is ambiguous ...; use a qualified name; switching to the qualified type name m.Tag binds each module’s own layout (see “Same-Name Tags” above). If the host defines a same-named type, the bare name belongs to the host (like rule ②).

Cross-module same-name coexistence: rule ③ lets two modules each define get without overwriting one another — at link time they coexist under synthesized symbol names (__<module-stem>__<name>), and each module’s internal call plus m1.get() / m2.get() binds back to its own definition.

Execution Model of Top-Level Statements

If an imported module contains top-level statements (statements outside any function or type definition), their execution follows:

  • Exactly once at first load: no matter how many times a module is imported, its top-level code runs only once.
  • Centralized topological order: all imported modules’ top-level statements are emitted before the main entry, in DFS-postorder of the dependency closure (dependencies run before dependents). The physical position of import lines in the main source has no effect on this order.
  • main of a non-main module is not a load hook: if a module defines main, it is treated as an ordinary function symbol and does not execute automatically.

Deduplication and Cycle Detection

  • Deduplication: the canonical absolute path is the unique key (case-insensitive on Windows); a module imported from multiple sites is loaded and merged only once.
  • Cycle detection: the loader performs DFS over the dependency graph; on detecting a cycle, it reports the full chain (e.g. cycle detected: a.co -> b.co -> a.co) and aborts compilation.

Example

Main source main.co:

import add, wrapper from "mod.co";
if (add(3, 4) != 7) return 1;
if (wrapper(2) != 7) return 2;
return 0;

Imported module mod.co:

static int helper(int x) { return x * 3; }
public int add(int a, int b) { return a + b; }
public int wrapper(int x) { return helper(x) + 1; }
printf("mod initialized\n");

Compilation and execution: mod initialized prints first (top-level statements emitted in centralized topological order), then the main source’s top-level statements execute in source order; the exit code is set by a top-level return.

Current Implementation Boundary (V0.4.1)

Implemented:

  • Full .co consumption pipeline (lexing / parsing / loading / per-module closure analysis / merging / visibility enforcement / linkage strip / entry-model integration);
  • Both named and * forms; import … as ModAlias enables qualified access;
  • Module-alias qualified access m.f() / m.f / m.x / m.x = v (with local write parity and const global write interception);
  • Independent module closures: per-module type/symbol isolation, same-name different-layout struct types never hijack each other;
  • Ambient cut-off: environment symbols brought in by a module’s #include do not enter its export surface;
  • Name-clash adjudication ①~⑧: shadowing / ambiguity / cross-module same-name coexistence (synthesized symbol names __<stem>__<name> at link time);
  • Centralized topological execution with first-load semantics; deduplication; cycle detection reporting the full chain;
  • Non-public imported symbols are forced to InternalLinkage during codegen;
  • Cross-module public struct / union / enum type references (usable as value-typed variables, member access, and address-of for passing) — identical in the main source and in submodules (since V0.4.1, by-value instantiation inside a submodule no longer degrades to an incomplete type);
  • Cross-module bare tags: a public struct/union/enum from an imported module may be referenced with the keyword omitted (Point p;);
  • Qualified type names mod.Tag (V0.4.1): accepted in every type-name position (declarations / struct keyword form / casts / sizeof / _Alignof / typeof / new), with struct/union/enum/class handled alike; same-name tags follow the three-stage scheme (definition-side warning + bare-name error + qualified names available); qualified enum constants (p.RED), qualified class statics (c.Counter::total) and qualified typedef (a.MyInt, only public typedef exported) ship in the same batch; since V0.4.1.47 qualified enum constants are also usable in compile-time constant positions (case labels, array lengths, enum initializers, global initializers), while bare enumeration constants still do not cross modules.
  • Cross-module compile-time constants: a public const int from an imported module (e.g. the WM_* series in winapi.co) is usable in the consumer as a plain read-only value, an array dimension, or a switch case label; globals that are not public const / not enum constants (including a cross-module public int) used as a file-scope initializer are rejected since V0.4.1.48 (initializer element is not a compile-time constant) instead of silently yielding 0; address-constant forms are unaffected; since V0.4.1.50 the rejection also covers aggregate member positions ({M, 1}/{[0]=M}/{{M}, 1}/{.in.x = M}), dereference and subscript (*(&M)/*o/*arr/arr[0]/*(&s.a)) and member access (oo.y/oo.in.x/op->in.x), matching clang line for line; since V0.4.1.52 it also covers explicit pointer-to-integer conversions ((long)arr/(long)&M/(long)add9; a same-object pointer difference without a cast, arr - arr, is unaffected), while loaded extern declarations and block-scope static initializers remain known gaps; since V0.4.1.53 array decay through a member (char *pc = oo.buf;, oo.m[1], g2[1] + 1) folds to a real address, the subscript and row-decay forms having been rejected in error before that version and now accepted like clang; since V0.4.1.55 a same-object pointer difference (&arr[1] - &arr[0] folds to 1) and the step width after a cast ((char *)arr + 1 steps 1, (void *)arr + 1 steps 1) fold to real values; since V0.4.1.57 an address-taken or decaying chain through a pointer (&op->buf[1], &(*op).buf[1], (*op).buf) is rejected on the same line as clang instead of silently folding a wrong address (taking the address of the pointer variable itself, &op, stays accepted); since V0.4.1.58 a cross-object pointer difference (other - arr, &M - &N, ex - arr, arr + 1 - other, an aggregate member position { other - arr, 0 } — operands whose addresses resolve to two distinct objects) used as a file-scope initializer is rejected on the same line as clang (the rejection shares its criterion with the folding side, so a same-object difference still folds to a real value); since V0.4.1.62 a pointer difference between incompatible pointee types (sa - arr, (long *)arr - (int *)arr, int (*)[3] - int (*)[4], enum E1 * - enum E2 *) is rejected by sema on the same line, column and text as clang ('X *' and 'Y *' are not pointers to compatible types, anchored at the - operator; compatible forms such as qualification differences and enum * ↔ int * are still accepted); in the same batch a difference between two void * operands no longer crashes the compiler and yields a value with GNU’s byte step, and pointer spellings in diagnostics now match clang (int (*)[4]/int **/unsigned char *); since V0.4.1.63 &function resolves to its real function prototype (&f gives int (*)(void)), so the incompatible-pointee wording and the assignment form now match clang line for line, differences between differently prototyped function names are reported instead of silently skipped, and the legal form (*&f)() no longer crashes the compiler; the bare-function-name decay form is closed since V0.4.1.67, and since V0.4.1.73 implicit pointer ↔ integer conversions (initializer/assignment/argument wording) match clang line for line (bool targets and null pointer constants stay legal); two known gaps remain — char * ↔ signed char *, and a pointer-to-floating conversion (float f1 = arr;, a different wording); the subscript base family matches clang since V0.4.1.75 for function designators and function pointers, and since V0.4.1.76 arithmetic and subscripting on a void * use a 1-byte step with the statement form vp[1]; no longer crashing the compiler (sizeof(void) / sizeof(vp[1]) are 1); since V0.4.1.77 a scalar-base subscript matches clang line for line too (anchored at the [ of the offending level), the incomplete-record form is closed since V0.4.1.79 (same line and wording as clang, anchored at the [ of that level, forward-declared enum still accepted); applying sizeof / _Alignof to an incomplete record is closed since V0.4.1.80 as well (the type form anchored at the keyword, the expression form at the first token after it); pointer arithmetic on an incomplete record is closed since V0.4.1.82 as well (binary forms anchored at the operator column, ++/--/+=/-= at the operator start, int x = ip + 1; reporting only the arithmetic line); since V0.4.1.84 void values in binary operations, assignments, initializers, arguments and ++/-- are rejected with the same line, wording and column as clang (operators are anchored at their own column, void-source initializers at the declarator identifier, including complex declarators and multiline initializers). Explicit discards stay accepted; returning a void expression from a void function follows clang’s default extension policy and preserves side effects. Remaining known gaps include unary/condition/non-void-result return uses of void values, 1 - ip in the separate invalid-operands family, and file-scope forms whose record is defined after the arithmetic;
  • DLL / WinMain top-level-init carriers: producing -o *.dll synthesizes a DllMain that runs each module’s top-level initialization under DLL_PROCESS_ATTACH (a user-authored DllMain is renamed and forwarded); under a GUI-exe WinMain entry, top-level statements and runtime-initialized globals are carried by a synthesized WinMain wrapper (see the “Module” chapter).

Reserved names: __init__*__ is a reserved prefix for the module-init dispatch protocol and cannot be defined by user code (compile-time error reserved protocol name '__init__*' cannot be defined by user code).

Not covered in this batch — deferred to later milestones:

  • .bc / .dll / .lib / .so / .obj as importable modules (all of them must carry compile-time declaration metadata); all of them currently get an explicit diagnostic (see “Import Target Suffix Whitelist”) rather than degrading into “module not found”;
  • User-authored __init__ customization.

Command Line

Invocation

colang [options] <source.co>

One invocation handles one source file. When no action option is given, the compiler builds and links an executable.

Options

OptionDescription
-h, --helpShow usage and the option list
-v, --versionShow the compiler version (four segments), the LLVM version used, and the target platform
-EPreprocess only; send the expanded token listing to standard output
-cCompile only; produce an object file (COFF .obj for a Windows target, ELF .o for a Linux target) without linking
-o <file>Write the output to <file>; when omitted, the name follows the “Output files and default names” section
-I <dir>Add a header search directory; may also be written -I<dir> and repeated
--target <triple>Set the target triple (e.g. x86_64-unknown-linux-gnu); defaults to the host platform when omitted
--resource <file>Embed a PE resource into the executable; may be repeated. Accepts a .rc (compiled by the built-in resource compiler) or a precompiled .res (embedded as-is). Windows targets only
-l <name>, --lib <name>Pull external library <name> in at link time; may also be written -l<name> / --lib=<name> and repeated. The name is a bare link name (e.g. -luser32). The only way for a pure .c translation unit to name an external library
-fno-diag-contextDo not print the source lines around diagnostics (by default the offending line ±2 lines are shown, with the column marked)

Output files and default names

ActionOutputDefault name when -o is omitted
Default (compile + link)ExecutableWindows: <source basename>.exe; other platforms: <source basename>
-c.obj object file<source basename>.obj
-EStandard outputAlways goes to standard output; -o has no effect

When -o is omitted, all of the default outputs above are written to the current working directory (the directory from which colang is invoked), not next to the source file. If the directory given to -o does not exist, the link step fails outright (cannot open output file ...); colang does not create the directory for you.

When linking, the intermediate .obj is written to the system temporary directory and removed automatically after the link.

Usage examples

All examples below are run from the command-line directory; outputs land in that same current directory:

colang hello.co                    # compile and link, producing hello.exe in the current directory
colang hello.co -o app.exe         # same, but rename the output to app.exe
colang -c hello.co                 # compile only, producing hello.obj in the current directory
colang -E hello.co                 # preprocess only, sending the expanded token listing to standard output
colang -I myinc hello.co           # add myinc as a header / import-module search directory
colang -luser32 app.c              # pull in external library user32 at link time for a pure .c unit
colang --resource app.rc app.co    # embed the PE resource app.rc, then link into app.exe

The four-segment version

-v prints something like:

colang 0.4.1.25
LLVM   23.1.0
target x86_64-pc-windows-msvc
model  LLP64 (windows) (long=4, void*=8, wchar_t=2)

The first three segments MAJOR.MINOR.PATCH are the release version; the fourth is a build counter, increased whenever the compiler is really rebuilt (and reset to zero when the three-segment version changes). It only tells development builds apart and does not signal a functional change. The PE version info (FILEVERSION/PRODUCTVERSION) of the produced exe/dll uses the same four segments.

Default settings header

Every compilation automatically expands include/colang.h from the standard library directory ahead of the main source (silently skipped when it is not found), so you can put your own global macro definitions there. The injection applies to the main source only, not to imported modules, and works the same in plain-C and .co mode.

What -E actually prints

-E prints a line-by-line token listing, shaped like:

hello.co:3:1  keyword     int
hello.co:5:12  string      "hello\n"

It is meant for inspecting macro expansion, conditional pruning and file inclusion; it is not C source that can be fed back into a compiler. Also, -E stops at preprocessing and performs no syntax checking: even if the source contains syntax errors, -E still prints tokens and returns 0.

In order of decreasing priority:

  1. Directories given with -I on the command line;
  2. The Co-provided standard header directory (stdio.h, stdint.h, winapi.co, …), located automatically: the environment variable COLANG_STDLIB is checked first (point it straight at the header directory); if unset, the compiler walks upward (at most 8 levels) from the directory containing the colang executable and locates that include/ directory by the presence of include/stddef.h.

The release package is a flat single-level layout — colang.exe sits next to the standard header directory include/, so it works out of the box after extraction: neither #include <stdio.h> nor import "winapi.co" needs -I. If you move the compiler elsewhere, keep colang.exe and include/ side by side, or point COLANG_STDLIB at the header directory. When the standard headers cannot be located, #include <stdio.h> fails with #include file not found.

Target platform and data model

colang drives the whole pipeline from a single target: predefined macros, type widths, code generation and linking all come from the same target triple. When --target is omitted the target defaults to the host platform (Windows/LLP64 on Windows, Linux/LP64 on Linux).

TargetData modellongvoid*wchar_tKey predefined macros
Windows x64LLP64482_WIN32 _WIN64 _MSC_VER __LLP64__
Linux x86_64LP64884__linux__ __gnu_linux__ __ELF__ __x86_64__ __LP64__

The data-model macros (__LLP64__/__LP64__) reflect the compiler’s real type widths and are strictly consistent with sizeof(long); standard-header typedefs such as size_t/ptrdiff_t and wchar_t are dispatched accordingly (on Linux size_t is unsigned long and wchar_t is 4 bytes, matching glibc). The width of long, together with every integer promotion and usual arithmetic conversion it takes part in, is likewise carried through the whole chain from the target (preprocessing, type inference, semantic analysis and code generation all read the same width), so on LP64 an expression involving long is evaluated as 64-bit and on LLP64 as 32-bit.

Cross-target compilation (for example --target x86_64-unknown-linux-gnu on Windows) can produce ELF object files and IR; but the linking step uses the linker backend of the platform the compiler was built on, so linking artifacts across platforms is not currently supported.

Beyond the target-specific macros above, colang always defines one target-independent identification macro __COLANG__ (value 1), present on every platform and under any --target, so sources can test “whether this is being compiled by colang” (in the same family as __clang__ and __GNUC__).

Linker: built in

colang ships its own linker, so turning sources into an executable needs no external clang and no linker command.

  • Windows: Linking requires the Windows SDK and the VC runtime libraries to be installed on the machine (they provide libcmt and other platform libraries). colang locates them automatically, so an ordinary command prompt is enough — a Developer command prompt is not required. By default the output statically links the C runtime, so an exe you build on your machine runs on Windows machines that do not have the VC redistributable installed.
  • Linux: The in-process linker (lld) statically links glibc and libgcc to produce a native ELF executable. colang automatically locates crt1.o/crti.o/crtn.o, libc.a and libgcc; you need the static library packages installed (Debian/Ubuntu libc6-dev). The search locations can be overridden with the COLANG_CRT_DIR, COLANG_LINUX_SYSROOT and COLANG_GCC_LIB_DIR environment variables. Statically linked executables are currently supported; dynamic PIE / .so are still under development.

Compatibility note: what you distribute is your compiled program (exe), not colang itself. No LLVM/clang tooling needs to accompany the program.

Naming an external library (-l / --lib)

Calling an OS API or any other external library requires telling the linker which library to look for. A .co source file can state it with the [[lib("X")]] attribute (see the “Attributes” chapter); a pure .c translation unit cannot write that attribute, so it uses the command-line switch instead:

colang -luser32 app.c
  • Four equivalent spellings: -l <name>, -l<name>, --lib <name>, --lib=<name>; the option may be repeated and duplicate names are deduplicated.
  • The name is a bare link name, the same convention as [[lib("X")]]: write user32, not user32.lib, C:\libs\user32 or user32.dll; a .lib suffix is tolerated (it is never doubled into .lib.lib).
  • Windows: each name becomes -defaultlib:user32.lib on the linker command line — the very same link directive that the [[lib]] attribute produces, so the two mix without conflict; library search paths are located by the linker from the local SDK / VC directories, and a missing library reports cannot open file 'xxx.lib'.
  • Linux: each name becomes -l<name> inside the static link library group.

Boundaries:

  • --lib affects the link step only; under -c it is ignored with a notice.
  • A name containing path separators, quotes, whitespace or a colon is rejected outright (no guessing a path from a library name).
  • It settles which library to pull in, not ownership of same-named symbols: when two libraries define the same symbol, their order decides which one is taken.

PE resource embedding

--resource embeds Windows resources (icons, version info, a manifest, …) into the produced exe and may be repeated; for example colang --resource app.rc app.co (give the .rc through --resource, not as the positional source file). Each item takes one file:

  • .res: a precompiled resource file, embedded as-is.
  • .rc: a resource script, compiled and embedded by colang’s built-in resource compiler — no external rc.exe needed.

A .rc script can #include "resource.h" for your own ID macros (system headers such as <windows.h> are not required and are skipped). The following resources are currently supported:

  • icons via ICON — automatically split and grouped, so the .ico file is given only once;
  • bitmaps via BITMAP;
  • arbitrary binary data via RCDATA;
  • an application manifest via MANIFEST;
  • version info via VERSIONINFO — fixed attributes (FILEVERSION, PRODUCTVERSION, FILEFLAGS, FILETYPE, …), plus VALUE text under STRINGFILEINFO and TRANSLATION under VARFILEINFO;
  • string tables via STRINGTABLE (and its STRING entries) — encoded as RT_STRING following rc.exe’s rules; multiple STRINGTABLE blocks in the same language may be declared across the script and are merged into the same group;
  • accelerators via ACCELERATORS — encoded as RT_ACCELERATOR with rc.exe’s per-entry 8-byte layout and its end-of-block fVirt 0x80 marker (reproduced for byte-for-byte parity); keys accept a quoted single character or a VK_* virtual-key name (the latter requiring VIRTKEY), the options VIRTKEY/NOINVERT/SHIFT/CONTROL/ALT accumulate as bit flags, and the command must be a numeric id after macro expansion;
  • extended dialogs via DIALOGEX — encoded as RT_DIALOG following rc.exe’s DLGTEMPLATEEX/DLGITEMTEMPLATEEX layout, byte-for-byte identical to rc.exe; the dialog header accepts x,y,cx,cy[,helpID] and the optional clauses STYLE/EXSTYLE (|-separated style expressions, which may use common WS_*/DS_*/WS_EX_* style macros or numeric values), CAPTION, MENU, CLASS, and FONT pt,"face"[,weight[,italic[,charset]]] (which automatically sets DS_SETFONT); controls include PUSHBUTTON/DEFPUSHBUTTON/CHECKBOX/RADIOBUTTON/AUTOCHECKBOX/AUTORADIOBUTTON/GROUPBOX/LTEXT/RTEXT/CTEXT/ICON/EDITTEXT/LISTBOX/COMBOBOX/SCROLLBAR (each mapping to a predefined class atom and rc.exe’s default style) plus the general CONTROL; a control may be followed by optional style/exstyle/helpID override values;
  • custom types and resource names: written as a numeric ID, a quoted string, or a bare identifier (a bare identifier is upper-cased and stored without quotes as a string name/type, matching rc.exe); plus per-resource LANGUAGE statements.

Qualifiers such as MOVEABLE and DISKFILEONLY are accepted and ignored (they do not affect the result); LANGUAGE statements take effect.

String literals in a .rc always follow rc.exe’s rules: to embed a double quote inside a string, write "" (doubled) rather than \" (rc.exe does not treat a backslash as escaping a quote). Recognized escapes are \t, \n, \r, \a (0x08), \\, octal \0–\7 (at most 3 digits), and hex \x (at most 2 digits); any other \X keeps the backslash literally.

The VERSIONINFO (VS_VERSION_INFO) produced by the built-in resource compiler is byte-for-byte identical to rc.exe’s; the fixed attribute FILEOS uses its given value when present and defaults to 0 when omitted (matching rc.exe).

Current boundaries:

  • Resource embedding applies only to the link output; with -c (compile-only) --resource is ignored with a note.
  • Only Windows targets are supported; cross-compiling to a non-Windows target reports an error.
  • Script-style resources — the classic DIALOG (non-EX form) / menus MENU — are not yet supported and produce a clear diagnostic; DIALOGEX styles/controls use a built-in table, so custom control classes, rare style bits, and long control creation data (creation data) not listed in the table are not yet handled.

Multi-file programs

A single invocation compiles one source file. colang composes several .co source files through the import mechanism (see the “import (Module Import)” chapter).

The single .obj produced by -c is useful for inspecting the compile result. Linking several object files directly into an executable is still under development; for now, organize multi-file programs with import.

Diagnostics and exit codes

Diagnostics are printed to standard error in the form file:line:column: error: message (advisory ones as warning). There are only two exit codes: 0 on success, 1 on failure.

Each diagnostic is followed by the offending line plus two lines on either side, with a ^ below the offending line pointing at the column:

app.c:4:9: error: use of undeclared identifier 'foo'
 2 | {
 3 |     int a = 1;
 4 |     a = foo + bar;
   |         ^
 5 |     return a;
 6 | }
  • One snippet per line: several diagnostics on the same source line share a single snippet instead of repeating it.
  • Traced to the real origin: when the error is inside a header #included by a .co source, the snippet shows that header’s own source and line number, not the corresponding position in the main source.
  • Can be turned off: -fno-diag-context falls back to one-line diagnostics, which keeps scripted output short.
  • When the position cannot be located in the file (for example at end of file), only the one-line diagnostic is printed.

Source files

Co source files use the .co extension by default (.cop for web-page based sources). A UTF-8 BOM at the start of a file is stripped automatically when it is read.

Current boundaries

  • -h also lists several options meant only for debugging the compiler itself (token, syntax tree and IR dumps). Their behavior and output format are not guaranteed to stay stable across versions, so this document makes no promises about them.

Development Roadmap

colang (the Co language compiler) follows a staged route: first fully implement a C compiler, then tailor and extend it into the Co language.

Version Policy

Versions follow MAJOR.MINOR.PATCH:

  • 0.* — Development and testing. Features and syntax may change; no cross-version compatibility guarantee.
  • 1.* — Official release. Public contracts are frozen; backward compatibility is guaranteed.
  • 2.* — Bootstrapping. The compiler itself rewritten in Co.
  • 3.* — Product finalization. Beyond bootstrapping, converged into a final, production-ready stable form.

Within 0.*, MINOR bumps denote milestones (a key Co-layer capability). PATCH bumps are small Co-layer prerequisites or C-base fixes between two milestones.

0.* Milestones

VersionThemeStatus
V0.1.0C compilerReleased
V0.2.0Co entry model + publicReleased
V0.3.0LinkingReleased
V0.3.1Windows GUI & winapi.coReleased
V0.3.2Linux native ELF toolchainReleased
V0.4.0classReleased
V0.4.1Diagnostics conformance & winapiReleased
V0.6.0Complex core slice + stdlib headers + linker diagnosticsReleased

Details for 1.* / 2.* / 3.* will be finalized by the maintainer before 0.* wraps up.

Released

V0.1.0 — C compiler

  • Full C17 coverage plus key C23 features (_BitInt, nullptr, auto, bool following C++ semantics, attribute syntax, etc.).
  • Hand-made colib standard headers to avoid cross-ABI dependencies.
  • Passes the Fujitsu c-testsuite conformance test suite.
  • Layered compiler structure: lexer → preprocessor → parser → sema → LLVM codegen, producing a single .bc that is handed to an external linker.

V0.2.0 — Co entry model + public

  • Top-level statements execute in source order; a user main is not required (the compiler synthesizes the entry).
  • Coexistence of a user-written main and the synthesized entry; top-level return V; sets the process exit code.
  • The public keyword marks exported symbols; -o *.dll / -o *.so selects the output kind by file extension.
  • Three-way entry rule: bare statements present → normal execution; only main → forward without warning; neither → warn and emit an empty ret 0.

V0.3.0 — Linking

First delivery covers import (.co source merge) and the linking core (checked items below); unchecked items roll to later milestones.

  • import (.co source merge): syntax import * | name [as alias], … from ("file" | module_name);; consumes .co sources only, public being the sole cross-module visibility gate; top-level statements of imported modules run once at first load, unified before the main entry in topological order; path dedup + DFS cycle detection reporting the full chain; identifier form from a equals from "a.co" (same directory only).
  • The compiler links on its own: -c emits a COFF .obj, and the default action links the object into an executable — no dependency on an external clang.
  • -o <name>.dll produces a Windows dynamic library: with an export table, and a .lib import library generated alongside the base name.
  • [[lib("user32")]] declares library attribution, with no command-line flag needed.
  • Static CRT linked by default: the produced exe ships without requiring the VC runtime to be installed.
  • Multi-module .obj merging, .dll / .lib consumption, static library output.
  • import extended to consume .obj / .dll / .lib as importable modules (bundling compile-time declaration metadata).
  • Module-alias-limited access: m.f(), m.x.
  • Refinement of DllMain synthesis and top-level body triggering for DLL outputs.
  • User-visible command-line arguments argv: delivered via route A (.co top-level entry has built-in argc(int) + argv(char**), C-form and self-contained, iterated by the argc count with argv[argc]==NULL), decoupled from the array-with-length infrastructure; argv as a globally visible, self-length-carrying string-array value type still awaits D37 (same batch as string/general arrays).

V0.3.1 — Windows GUI & winapi.co

  • Windows GUI subsystem and WinMain entry: [[subsystem("windows")]] or defining WinMain switches the artifact to a console-less GUI program; WinMain is mutually exclusive with top-level bare statements.
  • winapi.co replaces windows.h: a starting subset, expanded through V0.4.0 to 323 prototypes / 39 struct-union layouts / 396 constants (SDK-verified), library attribution via [[lib(...)]]; a practical subset of programmatic GUI APIs (window, message loop, memory-DC drawing, clipping, text metrics, system colors).
  • const consistency: read-only enforcement (diagnostics matching clang); public const int values flow across modules into array dimensions and switch case labels, with non-constant labels now rejected instead of silently folded to 0.
  • First batch of attribute semantics: [[nodiscard]] / [[noreturn]] in effect; [[deprecated]] same-position duplicates accepted first-wins.
  • C-conformance batch: designated initializers across the chain (chained designators, promoted anonymous aggregates, union hosts, mask-merged bit-field initialization, DFS continuation), sizeof/_Alignof in constant contexts, universal character names (\uXXXX/\UXXXXXXXX) in identifiers and literals, prefixed character constant typing, _Alignas context constraints and cross-declaration consistency, static_assert in more scopes.
  • Diagnostics quality: typedef alias spelling restoration, column alignment with clang, up-front diagnostics for by-value allocation of incomplete types.
  • Flat single-level release package: colang.exe + include/ (standard headers located next to the compiler, no -I needed).
  • Linux (WSL) build brought up: the colang compiler itself builds and runs its regression suite natively on WSL2/Debian (linking at this stage still relies on an external toolchain).
  • Bare tags in the Co layer (C++ style): in .co sources a struct/union/enum may be used as a type without its keyword (Point p;), including a public tag of an imported module.
  • Release version strings extended to four segments MAJOR.MINOR.PATCH.Build (the fourth is a build counter, shown by -v and in the PE version info of artifacts).

V0.3.2 — Linux native ELF toolchain

  • A single target/data-model abstraction (__LP64__/__LLP64__) drives predefined macros, type widths, code generation and linking, eliminating the front-end/back-end data-model split.
  • On Linux an in-process lld::elf statically links the local glibc/libgcc into a native ELF executable (no external linker); crt1.o/libc.a/libm.a/libgcc are located automatically.
  • --target <triple> cross-emits ELF object files and IR.
  • Native colang build on Linux (LLVM 23.1 built from source, X86+lld); the plct matrix aligned to the Windows baseline.
  • Built-in .rc resource compiler and the --resource embedding channel (byte-for-byte alignment with rc.exe); the per-module compilation model promoted (independent closure + same-name routing + qualified access); wchar_t/wint_t made target-aware across the chain; the synthesised DllMain carrier for DLLs; const diagnostics aligned with clang.
  • New default settings header include/colang.h preloaded automatically.
  • Follow-ups (long tail): .so shared objects, dynamic PIE, x86-64 SysV ABI edge cases, ELF mapping of winapi.co, glibc audit of all stdlib headers.

V0.4.0 — class

  • Reference type class with new instantiation and this member access.
  • Four lifecycle protocols: __new__ / __retain__ / __release__ / __delete__.
  • Automatic reference counting and heap-object reclamation; out-of-scope auto-free.
  • public extended to class members.
  • Static class members accessed via the class name with double colon (C::m()).
  • Delivered beyond the original plan: member and parameter types opened up (class handles, struct/union/array embedded by value; parameters borrow, members are owned by the host); the delete statement for forced destruction and cycle breaking; correct release on goto/break/continue path terminations.
  • Follow-ups (long tail): inheritance and virtual functions; cross-module consumption of a public class from an imported module; the class form under multi-obj (--per-module); automatic cycle breaking (currently done with delete).

V0.4.1 — Diagnostics conformance & winapi expansion

  • Diagnostics-conformance wave: compile-time errors/warnings and the diagnostic context realigned with clang and ISO C/C++, converging several silent-wrong-value/misjudgement sites (file-scope bool/integer constant folding now follows “nonzero is true”).
  • Diagnostics: every error/warning now shows the offending line with +/-2 lines of surrounding source and a caret; -fno-diag-context disables it.
  • CLI and source-surface tightening: new -l/--lib to specify external libraries; [[lib]] and class definitions restricted to .co sources (rejected in .c/.h).
  • Co-layer robustness: fixed the degradation/crash when using a cross-module public struct by value inside an imported module.
  • winapi.co continues to expand: up to roughly 356 prototypes / 45 struct-union layouts / 503 constants, adding the winsock (ws2_32) socket family, the crypt32 string-encoding family, and more.

V0.6.0 — Complex core slice + stdlib headers

  • C complex types float _Complex / double _Complex core slice: + - * / arithmetic, == != comparison, the constant I (_Complex_I), and the <complex.h> accessors creal / cimag / conj / cabs / carg / projection (with f variants). Transcendental functions such as cexp / clog / csqrt and the standalone _Imaginary type are not yet supported.
  • Link-time undefined symbol diagnostics now report the real call-site file, line and column.
  • <threads.h> adds the C11 timed functions thrd_sleep / mtx_timedlock / cnd_timedwait, and now includes <time.h> so struct timespec is visible.
  • Fixed duplicate public global declarations in one .co module making cross-module consumers read back the initial value.
  • Note: this release corresponds to the internal development cycle 0.5.5.

Planned

Planned Co-language-layer features for the 1.* line are registered below (each shipped in a backward-compatible manner); 3.* details will be finalized by the maintainer, and the 2.* goal follows.

Planned language-layer features (1.* line)

  • Built-in string / wstring value types: first-class string value types carrying an implicit length, directly comparable and concatenable, added at the Co language layer (beyond C).
  • Cross-module binary import: import currently consumes .co sources only; planned to consume .dll / .lib / .so / .a binaries directly (the production side is already in place).
  • class inheritance / virtual functions / RTTI: on top of the delivered class core, add single/multiple inheritance, virtual functions and runtime type information, with up- and down-casting.
  • Full winapi.co coverage: the Co modular wrapper of the Win32 API keeps expanding, ultimately covering the full API set via a metadata-driven auto-generation pipeline.
  • Structured exception handling (try / catch / throw) (deferred requirement): retained as a language-layer requirement; its design and semantics are not yet finalized or scheduled — this entry registers intent only and is not a release or compatibility commitment.

V2.0.0 — Bootstrap

  • Goal: rewrite the colang compiler’s main body in the Co language itself, so the resulting compiler can compile its own source (bootstrap) — transitioning from today’s C++ implementation to a version written in Co that closes the loop by compiling itself.
  • Prerequisites: the Co language layer must be complete, correct and fast enough to express an entire compiler; the back-end must first be settled — either bind through a pure-C interface (LLVM-C) and link prebuilt libraries, or replace LLVM with a self-owned back-end (full bootstrap); and the whole build chain must be able to compile colang with colang itself. (Inheritance / virtual functions / exceptions are not prerequisites of bootstrap, only optional language conveniences when writing a compiler, and are already listed among the 1.* features above.)
  • Significance: bootstrap is the foundation for reaching product finalization (3.*) — once the compiler can compile itself, it sheds dependence on an external C++ toolchain and enters a long-term self-maintaining stage.

Terminology

  • Internal development documents use “milestone”.
  • Public-facing manuals (this one) use “release version”.
  • Feature wording and error messages reflect actual compiler behavior.

Changelog

This record lists major changes to the Co (colang) language/compiler by release version. Versioning policy: 0.* = development/test releases, 1.* = official releases, 2.* = bootstrap.

V1.0.0

  • Official release.

V0.7.0

  • class now supports properties: a class member can be defined as a property via an accessor pair — int a { get { return _a; } set { _a = value; } }; reading obj.a / writing obj.a = x uses the same syntax as an ordinary field and dispatches to get / set automatically. Read-only (only get), write-only (only set) and auto-property sugar (int b { get; set; }, where the compiler synthesizes a hidden backing field) are supported; inside an auto-property’s accessor the contextual keyword field reads/writes that backing storage directly (matching C# 14 style). obj.prop++ / -- (prefix / postfix) and compound assignment obj.prop += x all expand correctly as “read, modify, write”; a property has no independent storage address, so taking its address (&obj.prop) is an error.
  • New private keyword + accessor-level visibility: private is explicit sugar (semantically equivalent to omitting public; cross-module visibility is still governed by the single public gate) and may precede members / methods / properties at the top level, the class header, and inside the class body; public and private together on one declaration is an error. Each property accessor can carry its own visibility (e.g. public int a { get; private set; }) — an accessor marked private may be called only inside the class that defines it, and external read/write is rejected per read-only / write-only.
  • Returning an owned class handle auto-retains: a function / method can now directly return a class handle already held by a local variable or member; the compiler adds one reference-count increment, eliminating the previous double-free crash when returning an owned handle. This form was formerly rejected at compile time (“a function returning a class must return an unowned value”) and is now allowed. Read/write of handle-typed properties (whose type is a class) now participates correctly in reference counting.
  • Full type checking of class method bodies: class methods and accessor bodies now receive the same level of checking as function bodies — undeclared identifiers, assignment and argument type compatibility, method-call argument count, unused variable / parameter warnings, missing return in a non-void function, and other issues previously missed in method bodies are now diagnosed with wording and line/column positions aligned to clang (previously an undeclared name in a method body slipped through to a bare undefined symbol at link time).
  • Fix a class of compile-time misrejections in aggregate initialization: when a struct is partially initialized with a string literal for a char array and later members follow (e.g. struct { unsigned char m1[3]; unsigned long m3; } b = { "12" };), and for ordered initialization involving unnamed / zero-width bit-fields, these were previously misjudged as type mismatches and rejected; they are now accepted like clang, with runtime values identical character-for-character. Known limitation: a union whose first member is an unnamed bit-field, and constant placement for a global initializer mixing “bit-field + zero-width bit-field + nested struct”, remain unsupported — such forms give a loud compile error rather than a silent wrong value.
  • winapi.co continues to expand: added the service-control, desktop / window-station, named-pipe, and network-interface-table (GetIfTable2 / MIB_IF_ROW2 / MIB_IF_TABLE2) API families and struct layouts; the total now stands at about 565 Win32 API prototypes and 78 struct / union layouts, with about 12,600 constants (including the full winerror.h error-code mirror).

V0.6.1

  • winapi.co constants greatly expanded: Win32 constants grow from a few hundred to roughly 12,600, including a full mirror of the winerror.h error codes (7416 entries, line-by-line against Windows SDK 10.0.26100.0 shared\winerror.h) and the user32 window / message / style, CommCtrl common-control, edit-box / menu / scrollbar / tray / hotkey families. Every entry was verified against SDK 10.0.26100.0 with 0 wrong values.
  • winapi.co fixes 18 mismatches with the SDK: 14 function prototypes’ return / parameter types (e.g. SetLastError returns void, CreateSemaphoreW returns HANDLE, GetAsyncKeyState returns SHORT), 1 constant value (IDC_NO), and 3 struct layouts (LOGPEN rewritten per SDK, MODULEENTRY32W field names, WSADATA.szSystemStatus length); before these fixes, calling these APIs could silently pass wrong arguments or read wrong values.
  • [[subsystem("windows")]] can now be written at the top of a source file (application scope): previously the attribute only took effect when attached to the main / WinMain function; it can now be written as a standalone directive at the top level of a .co file, so a Windows GUI program can be produced from the directive plus import and top-level bare code — the “minimal Windows GUI example” in the docs (file-level [[subsystem("windows")]] + import * from winapi; + bare MessageBoxA) now works. It takes effect only in the main module; the attribute in an imported module is ignored with a warning.
  • winapi.co internal restructure (transparent to users): the monolithic winapi.co is split into an umbrella trio (winapi.co + internal parts winapi_core.co / winapi_winerror.co) merged back via #include text inclusion — existing import … from "winapi.co" is unchanged and keeps working, with no user code needing modification.

V0.6.0

  • C _Complex support (core slice): .c / .co now support the float _Complex / double _Complex types, + - * / arithmetic, == != comparison, the constant I (_Complex_I), and the <complex.h> accessors creal / cimag / conj / cabs / carg / projection (with f variants). This batch is a core slice: transcendental functions such as cexp / clog / csqrt and the standalone _Imaginary type are not yet supported; int _Complex is an error when written; __STDC_NO_COMPLEX__ remains defined, so portable code that relies on it to skip complex behaviour is unchanged.
  • Linker errors now report the source location: link-time undefined symbol previously always pointed at <obj>:1:1 with no source line; each undefined symbol is now resolved back to the real call-site file, line and column (falling back to the old form only when it cannot be located).
  • <threads.h> adds the C11 timed functions: thrd_sleep / mtx_timedlock / cnd_timedwait are now provided; and <threads.h> now includes <time.h>, so struct timespec is directly visible without the user including the header themselves.
  • Fix duplicate public global declarations in one module making consumers read the initial value: previously, declaring the same public global variable twice in one .co module split the module-internal instance from the exported one, so consumers read the initial value (0) instead of the latest; the two declarations now resolve to a single instance.

V0.5.4

  • ptr - ptr pointer difference fixed to 64 bits: subtracting two pointers was truncated to a 32-bit int, so a span over 2 GiB came out negative or wrong; it now returns a 64-bit value like clang, and sizeof(p - q) is corrected from 4 to 8.
  • Referencing a public struct no longer crashes: when a public struct had a member type not marked public, the importing compiler used to crash outright; it now gets the size correctly and reports a clear error only when expanding the non-exported member’s fields. Member types referenced by a public struct should still be marked public.
  • math.h adds declarations for copysign, nan, nextafterf and 2 more (5): these lacked prototypes, so calls were treated as returning an integer and silently produced wrong values; they are now declared and compute correctly.
  • float.h adds C23 floating-point feature macros: new macros such as FLT_DECIMAL_DIG, DBL_DECIMAL_DIG, FLT_EVAL_METHOD and FLT_HAS_SUBNORM (9 in total) for feature detection.
  • #if now compares unsigned values correctly: u-suffixed constants and unsigned values over 32 bits were evaluated as signed inside #if, giving wrong results (e.g. #if 2147483648u > -1 tested false); this now matches clang and tests true.
  • winapi.co constants corrected: 6 wrong values fixed (among them STD_INPUT_HANDLE / STD_OUTPUT_HANDLE / STD_ERROR_HANDLE were misaligned, so GetStdHandle(STD_OUTPUT_HANDLE) got the wrong handle) and 6 names that do not exist in the SDK removed. Code using these constants will change behaviour.

V0.5.3

  • The top-level type aliases in winapi.co are now usable across modules: 36 aliases — DWORD / WORD / BYTE / BOOL / HANDLE / HWND / LPARAM / WNDPROC and the rest — were not marked public, so even after import * from winapi; they still produced use of undeclared identifier (and variables declared with those aliases were cascaded into the same error). All 36 are now public typedef, so imported names can be declared and used directly. Behaviour change to note: these names now take part in cross-module same-name detection — if the imported module and the importing side each declare a typedef or a tag with one of these names, they clash.
  • Calling a non-public function across modules is now a compile-time error: calling a function that another module defines with a body but did not mark public used to compile fine and then fail at link time with a bare undefined symbol: X (no source position); it is now rejected at compile time with cannot import non-public symbol 'X' plus source context for the offending line. The rule covers only functions that have a body and are not public; non-public pure declarations such as [[lib]] / external C library prototypes are still allowed.
  • Argument-count checking tightened (now including external API declarations): previously only functions with at least one parameter and a body were arity-checked. From this release, hand-written external API prototypes (no body) and zero-parameter functions int f() / int f(void) are checked too and report too many arguments / too few arguments — they used to pass silently and emit the call with the wrong arguments (mismatched registers/stack; when a [[lib]] import hit a real export, even linking succeeded). setjmp(env) is exempt by name (its setjmp.h prototype takes 2 parameters, and the compiler injects the second).
  • Function prototype semantics now follow C23 (() is equivalent to (void)): an empty parameter list is a zero-parameter prototype, and the whole legacy “non-prototype declaration” compatibility rule set is removed. void f(void); void f(int); is now a declaration conflict; void f(); void f(int a) { … } (previously accepted) is now rejected; calling a parameterless f() with arguments now reports too many arguments. K&R-style definitions remain unsupported. Behaviour change to note: code relying on legacy non-prototype declarations turns into compile errors — matching what clang -std=c23 decides.
  • public typedef struct X Y; now has complete types inside non-root modules: after importing the module, sizeof(Y) / a local Y y; used to be falsely reported as incomplete, and p->a member access or an f(Y h) by-value parameter could even crash the compiler (0xC0000005, no diagnostic); using Y inner; as a struct value member failed only in LLVM verification. From this release the five alias forms are fully equivalent to the struct X tag form; genuinely incomplete types are still rejected in the front end with clang-matching diagnostics.

V0.5.2

  • math.h gains the long double maths declarations (all 56 of the C standard family): the l-suffixed functions — asinhl / acoshl / atanhl / sqrtl and the rest — had no declarations at all in math.h. Following the C implicit-function-declaration rule, colang treated an undeclared function as returning int, so the call site read a floating-point result out of an integer register: compilation and linking both succeeded with no diagnostic, while the program produced garbage integers (which could even differ from run to run). This release adds all 56 l-suffixed declarations, each prototype taken verbatim from the Windows UCRT header (including the host-specific spellings: nexttowardl’s second parameter is long double, ilogbl returns int, lrintl/lroundl return long, llrintl/llroundl return long long, and scalblnl’s second parameter is long). Correctness fix: code that called these functions and received wrong values now receives the right ones.
  • New minimal complex.h: #include <complex.h> used to fail outright because the standard library shipped no such header. This release delivers complex.h, which defines __STDC_NO_COMPLEX__ per the C standard (honestly reporting that complex support is absent). colang still does not implement the _Complex / _Imaginary types, and this header deliberately does not define I — defining I as a real number would let 1.0 + 2.0 * I silently evaluate to 3.0 (a wrong value with no diagnostic at all); sources that really use complex constructions still get explicit diagnostics instead of degrading into real arithmetic. Programs that merely include the header without using complex constructs now compile and run normally.

V0.5.1

  • Warning-diagnostic classification system landed: added the command-line flags -Werror (promote warnings to errors) and -Wno-<group> (silence a specific warning by group name); every warning is now trailed by its group tag [-Wxxx], so they can be toggled precisely.
  • Several clang -Wall / -Wextra warnings added: new -Wunused-variable, -Wunused-function, -Wunused-but-set-variable, -Wswitch (an enum switch that does not cover all enumerators and has no default), and -Wunused-parameter, each verified case by case against clang; also fixed a bug where a warning was emitted twice for a call to a forward-declared function with no body.
  • Bit-field and integer-width diagnostic conformance: spellings that were previously accepted silently — bit-field widths, _BitInt / wchar_t unit widths, redefinition in the same scope, and for / if / switch init-statement scopes — are now all rejected with clang-matching wording and line/column positions.
  • Major winapi.co expansion: on top of V0.5.0 it adds process/thread enumeration, Shell/clipboard/process operations, Hook/keyboard/mouse input, resource loading/power/user name, synchronization objects/memory-mapped files/named pipes, file attributes/volume information/security tokens, heap/process times/handle duplication/IO control, priority/console/environment strings/symbolic links/disk space, console mode / VirtualQuery, registry enumeration/deletion, and named sync objects/waitable timers/heap operations/page locking, among others; the module now totals about 481 Win32 API prototypes, 72 struct/union layouts and 815 constants. Every struct layout was verified line by line against Windows SDK 10.0.26100.0 via sizeof / offsetof.

V0.5.0

  • long / unsigned long in .co sources is now 8 bytes (Windows target); long and long long are now the same type. .c / .h are unchanged and still follow the target data model (4 bytes on Windows / 8 on Linux). Three migration consequences: ① long and long long can no longer both appear in one _Generic; ② taking the address of a .co long variable and passing it to an API prototype declared with int / unsigned int (winapi.co follows the SDK spellings and never uses long) is now rejected as incompatible pointer types; ③ printing a 64-bit integer requires %lld — %ld reads only 4 bytes and yields a wrong value.
  • winapi.co constants corrected and expanded (every one of the 509 constants in the section was re-verified numerically against Windows SDK 10.0.26100.0): SM_CXSCREEN 78→0, SOMAXCONN -1→0x7FFFFFFF, FILE_NOTIFY_CHANGE_LAST_WRITE 0x8→0x10, PATCOPY 0x00F00062→0x00F00021 — code using these four constants changes runtime behaviour, since it previously passed wrong values. Also added FILE_NOTIFY_CHANGE_SIZE, SM_CYSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SM_CXVIRTUALSCREEN and SM_CYVIRTUALSCREEN, so locally re-declared stand-in constants can go back to the winapi.co ones.
  • Literal and type-specifier diagnostic conformance: the spellings below were silently accepted, folded to wrong values, or crashed the compiler with no diagnostic at all; they are now all rejected, with message text and line/column positions matching clang case by case: ① truncated exact-width suffixes (1w, 0x1w → invalid suffix 'w' on integer constant); ② signed / unsigned on floating-point types (signed float, unsigned double → 'float' cannot be signed or unsigned); ③ mixed-case suffixes (1lL, 1wB, 1.0lF); ④ illegal digit strings (0b2, 08, 1f); ⑤ a missing exponent digit (1e, 0x1p) and hexadecimal floating constants missing a significand or an exponent (0x., 0x1.5); ⑥ integer literals wider than unsigned long long (18446744073709551616, 0xFFFFFFFFFFFFFFFFFFFF). Valid spellings are unaffected: 1uwb / 1UWB / 0b1010wb, 1.0f / 1.0L, 08.5 / 09e1 and 9223372036854775808 (typed unsigned long long) are still accepted.
  • winapi.co batch XIII expansion and two return-type corrections: corrected SendMessageA’s return type int→long long (SDK returns LRESULT, 8 bytes on x64; the old spelling truncated the high 32 bits of the return value) and RegisterClassA’s return type short→unsigned short (SDK returns ATOM=WORD; window-class atoms always land in 0xC000–0xFFFF and read as negative when taken as short). Added the WNDCLASSW struct, 18 prototypes (user32 CreateMenu/GetMenu/SetMenu/GetSubMenu/EnableMenuItem/RegisterClassW/UnregisterClassW/RegisterHotKey/UnregisterHotKey/LoadStringW; kernel32 CopyFileW/RemoveDirectoryW/GetFileSizeEx/FormatMessageW/LocalAlloc/LocalFree; gdi32 GetTextMetricsW; comdlg32 GetSaveFileNameW) and 37 constants each verified line by line against Windows SDK 10.0.26100.0 (MOD_*/WM_HOTKEY/VK_F1..F4/MF_*/FORMAT_MESSAGE_*/LMEM_*/GENERIC_*/CREATE_*/FILE_*/ERROR_*, etc.), bringing the module to 374 prototypes / 46 struct-union layouts / 546 constants. A “known boundaries” section at the end of winapi.co documents the compiler-layer limits still outstanding for consumers.
  • Windows x64 by-value struct/union ABI fix: the compiler used to lower every by-value struct/union parameter and return to ptr, which does not match the winx64 ABI (aggregates of ≤ 8 bytes must be packed into a single general-purpose register; only larger ones take an implicit byval pointer). colang’s caller and callee sides shared the same lowering so internal calls stayed self-consistent — the mismatch only showed up when calling external Win32 APIs. Now aligned with clang: aggregates whose store size is 1/2/4/8 are lowered to the matching integer scalar (i8/i16/i32/i64) at the signature boundary; larger or non-power-of-two sizes stay as ptr (the correct Microsoft x64 “pass by reference” lowering). WindowFromPoint(struct POINT) behaviour is corrected; SetFilePointerEx(union LARGE_INTEGER) is added to winapi.co; the corresponding item in the “known boundaries” section is flipped to fixed. Remaining boundaries: the 16-byte pure-integer aggregate “two-register” special case, and external APIs with >8-byte aggregates, are still passed by pointer. Non–Windows-x64 targets are unchanged byte-for-byte.

V0.4.1

  • Diagnostics-conformance wave: compile-time errors/warnings and the diagnostic context were realigned with clang and ISO C/C++, converging several silent-wrong-value/misjudgement sites (file-scope bool/integer constant folding now follows “nonzero is true”).
  • Diagnostics: every error/warning now shows the offending line with +/-2 lines of surrounding source and a caret; -fno-diag-context disables it.
  • CLI and source-surface tightening: new -l/--lib to specify external libraries; [[lib]] and class definitions are restricted to .co sources (rejected in .c/.h).
  • Co-layer robustness: fixed the degradation/crash when using a cross-module public struct by value inside an imported module.
  • winapi.co continues to expand: from V0.4.0’s 323 prototypes / 39 struct-union layouts / 396 constants up to roughly 356 prototypes / 45 struct-union layouts / 503 constants, adding the winsock (ws2_32) socket family, the crypt32 string-encoding family, and more.

V0.4.0

  • The class reference type (heap-only + automatic reference counting): instantiation via new, member access via this, instance methods and static members via C::m(); handles are released in reverse frame order when leaving scope, and break/continue/goto path terminations release them correctly.
  • Member and parameter types opened up: primitives, class, struct/union/arrays all work — a struct/union/array member is embedded by value (not reference counted, allocated and freed with its host); a class handle as a parameter borrows (ownership is not transferred), as a member it is owned by the host (assignment takes ownership, the destructor releases cascadingly).
  • The delete statement: forced destruction (bypasses the count — destructor + cascading release + free); the slot is null-ed to prevent a double free; it can also be used to break reference cycles manually.
  • public class: in a single module and under -o *.dll, exports the lifecycle protocols, the instance/static methods and the members.
  • Current boundaries: no inheritance and no virtual functions; a public class in an imported module cannot yet be consumed across modules; reference cycles are not broken automatically (use delete).
  • Major winapi.co expansion: 323 Win32 API prototypes, 39 struct/union layouts and 396 constants, each re-verified against Windows SDK 10.0.26100.0; beyond the window/message-loop/drawing base it now adds dialogs, menus, common controls, tray icons, DWM, PDH, input method (imm32), file-time/directory enumeration and more.
  • Bare tags in the Co layer (C++ style): in .co sources a struct/union/enum variable definition, parameter or sizeof may drop the keyword (Point p;), and a public tag of an imported module may be used bare as well; not enabled for .c, which stays byte-for-byte ISO C.
  • Version strings extended to four segments MAJOR.MINOR.PATCH.Build: the fourth is a build counter increased by a real MSVC rebuild (it resets to zero when the three-segment version changes); -v output and the PE version info of artifacts follow suit.
  • New default settings header include/colang.h: expanded ahead of the main source at compile time (main source only, not for imported modules), for your own global macro definitions.

The last three items above (bare tags, the four-segment version, the default settings header) were already-shipped changes that never got recorded — the first two landed within the V0.3.1 cycle, the third in the V0.3.2 cycle; they are back-filled here.

V0.3.2

  • Built-in resource compiler: parses .rc syntax, supports ICON / BITMAP / RCDATA / STRINGTABLE / VERSIONINFO / ACCELERATORS / DIALOGEX / MENU resource types; output embedded directly into the PE executable (byte-level alignment with rc.exe).
  • Linux cross-compilation & native linking: --target=x86_64-unknown-linux-gnu emits ELF objects; the in-process lld ELF linker provides end-to-end executables; LP64 data model (long=8, void*=8, wchar_t=4) correctly dispatched.
  • Per-module compilation model promoted: each module compiles as an independent closure, cross-module same-name symbols are automatically routed (no collision); qualified access mod.func() / mod.var supported.
  • wchar_t fully target-aware: width and signedness follow target (Win unsigned short 2 bytes / Linux int 4 bytes); wint_t, L'…' overflow judgement, and TC-prefixed characters dispatch correctly.
  • const diagnostics aligned with clang: read-only violations now carry note: … declared const here pointing at the declaration site; new -Wdefault-const-init warning (function-local const objects or those with const members without initializer).
  • DLL production: synthesised DllMain entry carrier, top-level initialisation code driving, public functions written into the export table.
  • Multiple fixes in integer literal type selection, bit-field masking, and dynamic CRT linking.

V0.3.1

  • The winapi.co module: import … from "winapi.co" replaces windows.h, an SDK-verified set of Win32 API prototypes / struct-union layouts / constants; the module grows across releases and totals 323 prototypes / 39 struct-union layouts / 396 constants as of 0.4.0. First introduced covering common GUI APIs for window creation, message loops, drawing and text metrics.
  • Windows GUI programs: the [[subsystem("windows")]] attribute (or defining WinMain) produces a console-less windowed program.
  • Co-layer enhancements: public const int / public struct etc. from an imported module can be used across modules directly; designated initializers support chained designators and anonymous union members.
  • C compatibility: universal character names (\uXXXX) in identifiers; u8/u/U/L prefixed character constants; sizeof(string literal); static_assert in multiple scopes; the [[nodiscard]]/[[noreturn]]/[[deprecated]] attributes.
  • Diagnostics: const read-only enforcement, up-front incomplete-type diagnostics and rejection of non-constant switch case labels, with wording aligned to mainstream compilers.
  • Fixes: two families of runtime crashes caused by global initializers being mis-folded to null.
  • Release package flattened to colang.exe + include/ (no runtime redistributable, no extra configuration); native Linux (WSL) build brought up.

V0.3.0

  • Built-in linker: -c emits a COFF .obj, and the default action links the object into an executable — no dependency on an external clang.
  • Static CRT linked by default: the produced exe ships without requiring the VC runtime to be installed.
  • -o <name>.dll produces a Windows dynamic library: with an export table, and a .lib import library generated alongside the base name.
  • [[lib("user32")]] declares library attribution, with no command-line flag needed.
  • Linking requires a locally installed Windows SDK / VC runtime (auto-located).
  • import (.co source merge) landed:
    • Syntax: import * | name [as alias], … from ("file" | module_name) [as ModAlias];;
    • Consumes .co sources only; public is the sole cross-module visibility gate;
    • Top-level statements run exactly once at first load, unified before the main entry in DFS-postorder topological order;
    • Normalized absolute path dedup; DFS cycle detection reporting the full chain;
    • Identifier form from a is accepted, equivalent to from "a.co" (same directory only).
  • Referencing a non-imported symbol from the main source is rejected; importing a non-public symbol via named or * form is rejected.
  • Non-public imported symbols are forced to InternalLinkage during codegen (no externally-visible LLVM value is emitted).

See the “import (Module Import)” and “Module” chapters for semantics.

V0.2.0

  • Added bare top-level code, public functions, and import support;
  • Added DLL/SO generation;
  • Fixed several issues against the C language test suite.

V0.1.0

A development/test release; the C language compiler is complete.

  • The compiler supports C compilation; Co’s object-oriented and other extensions (such as class) are at the specification/planning stage and are not yet implemented.

V0.0.x

Development/test versions (historical). Features and syntax followed the then-current test versions and are not a release baseline.