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-levelreturnand 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 entryWinMainand the[[subsystem("windows")]]subsystem switch are implemented since V0.3.1; the top-level built-in command-lineargc/argvare 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:mainis 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 variantwWinMainis not yet supported). The return value is the process exit code. - Defining
WinMainautomatically 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). WinMainis mutually exclusive with top-level bare statements: a file with bothWinMainand top-level bare statements is a compile error (put the GUI logic insideWinMain);WinMainmust 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:
| Situation | Exit code |
|---|---|
A top-level return V; is reached | V, and the whole program ends immediately (later top-level statements and main are not run) |
Top level finishes with no return, and a main exists | main’s return value |
Top level finishes with no return, and no main exists | 0 |
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:
argcis anint, the number of arguments (including the program name itself, soargc >= 1);argvis achar**(a pointer to strings);argv[0]is usually the program’s own path, followed by the arguments in order;- iterate by the
argccount;argv[argc]is alwaysNULL(guaranteed by C).argvis a raw pointer, carries no length property, and has no bounds checking (C semantics) — keep within range usingargcyourself; - both are scoped to the synthesized entry’s top-level code: referencing
argvin a.cfile, in a shared-library artifact (-o *.dll/*.so), or under the GUIWinMainentry 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
argva globally visible, self-length-carrying string-array value type (readable inside functions and methods, with noargc) depends on Co’s array-carries-own-length infrastructure (same batch asstring/general arrays) and is not yet provided; for now it ships as the C-formargc+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
importlines in the main source has no effect on this order. mainof a non-main module is not a load hook: if a module definesmain, 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
mainalso exists,mainis entered automatically after all top-level statements finish, andmain’s return value becomes the exit code. return V;at the top level ends the whole program immediately with exit codeV; a barereturn;uses exit code0.- 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 code0. - 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
WinMainin the source takes the GUI entry (no console); or mark the entry function with[[subsystem("windows")]]to switch to the windows subsystem.WinMainis mutually exclusive with top-level bare statements and must take 4 parameters. - Command-line arguments (since V0.5.5): the
.cotop-level entry (synthesized consolemain) has built-inargc(int)/argv(char**), iterated by theargccount withargv[argc]==NULL; valid only as built-in names in the synthesized entry’s top-level code (referencingargvin.c/-o *.dll/*.so/WinMainreports undeclared); an explicitmain(pure C style) still receives argc/argv as parameters.
Not yet provided:
argvas a globally visible, self-length-carrying string-array value type (readable in functions/methods, noargcneeded) is not yet provided; it depends on the array-carries-own-length infrastructure (D37, same batch asstring/general arrays). For now it ships only as the C-formargc+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. voidmeans the function returns no value.voidmay 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[]andint a[10]are equivalent toint *a, sosizeof(a)inside the function yields the pointer width, not the array length. - A variadic function ends its parameter list with
...and reads the arguments throughva_start/va_arg/va_endfrom<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:
| Form | Meaning |
|---|---|
[ 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 omitted | The 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
voidmust produce a value before it finishes. - A
voidfunction may omitreturnentirely, or use a barereturn;partway through to end early. - Inside a function body,
returnends 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
voidfunction must notreturn a value, and a non-voidfunction must not write a barereturn;. The compiler rejects both. - A function body may contain several
returnstatements (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++
| Aspect | Co | Compared to |
|---|---|---|
Typed parameters, pass by value, return | inherited | same as C |
static / extern storage classes, function pointers | inherited | same as C |
| Definition order | irrelevant; a call may precede the definition | differs from C (C requires a prior declaration) |
| Omitting the return type | not allowed | same 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 templates | not provided | differs from C++ |
public | expresses “module interface / export”, not an access region | differs 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 onf()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:
publicon 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 publicin either order is legal. Since V0.3.0,publicalso serves as the sole cross-module visibility gate: symbols not markedpubliccannot be reached byimport(both named and*forms reportcannot import non-public symbol); non-publicimported symbols are forced toInternalLinkageduring codegen. In this batch,publicstill does not change linkage within the same TU (non-publicremainsExternalLinkageby default, matching P211); “module-internal” is still expressed by omittingpublic(see the “Module” and “import” chapters).- Sequential execution of top-level commands is implemented (entry dispatch, optional
main, top-levelreturnand 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:
| Attribute | Applies to | Effect |
|---|---|---|
[[lib("X")]] | top-level function declarations, global variable declarations | declares that the symbol is supplied by external library X; the linker pulls X in automatically |
[[deprecated]], [[deprecated("message")]] | top-level functions, global variables | emits 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 functions | verifies 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/.COsource files only:[[lib]]is a Co-defined attribute, so any other origin — a.c/.hfile, 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.his not relaxed just because a.coincludes it. Putting library ownership in a shared header for several.cofiles 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
publicandstatic:publicis export,libis import — they cannot fall on the same symbol;staticmeans 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.
deprecatedon 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: reasonis 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.
[[subsystem("windows")]] — switching the link subsystem
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 (
mainorWinMain); 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
WinMainalready 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' ignoredwarning 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++
| Aspect | Co | Compared to |
|---|---|---|
Attribute spelling [[...]] | adopted from C23 | same 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 effect | differs from C23 (C23 has real semantics) |
[[lib("X")]] | newly defined by Co; no such attribute in the C standard; and .co/.CO source files only | Co-specific |
[[subsystem("windows")]] | newly defined by Co; no such attribute in the C standard | Co-specific |
<: ::> alternative spelling | not supported | differs from C23 |
Compatibility note:
[[lib("X")]]is a Co-defined attribute. When a real clang/clangd reads.cofiles, it warns-Wunknown-attributesand ignores it — this is necessarily so, not a defect; external tools will not validate library ownership, only the Co compiler consumes it.- 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.cofiles — a pure.ctranslation 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.[[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.[[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·uniontype /typedef(observable viasizeof,_Alignof,offsetof), matching the local clang-std=c23verbatim. It is a one-way promotion only: alignment becomesmax(natural alignment, N)and is never lowered.Nmust be a power of two, otherwise it is an error (same as clang).packed— given real semantics (since V0.5.0): applied to astruct/uniontype or to a field, it really changessizeof,_Alignof,offsetofand the emitted layout (members without an explicitly declared alignment are laid out compactly at 1 byte), matching the local clang-std=c23value for value. Four boundaries, stated as they are: (1) an explicitly declared alignment wins — the member’s own_Alignas(N), or a type-levelaligned(N)carried by the member’s type, still aligns that member toN(packedonly compresses natural alignment, never an explicit one); (2) it binds only where it really takes effect — between thestruct/unionkeyword and its tag name, after the closing}, and after a field name; written before the declaration specifiers, after a variable name, after atypedefname, 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" …, wherestructfollows the keyword); (3)packeddoes 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 : 4still occupies 4 bytes / an i32) andpackedonly compresses the unit’s placement alignment to 1; a zero-width:0merely 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 withpackedand 8/4 naturally, matching the local clang value for value). The separate#pragma packpath 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 (packedhas had real semantics since V0.5.0 and no longer belongs to this tier). Text shaped likegnu 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 likegnu attribute 'noinline' ignored (non-standard, GCC/Clang compatibility).
- Strong warning (may affect memory layout / calling convention / linkage): the calling-convention family (
- 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):
- Real GCC/Clang fully implement these attributes; Co currently honors
alignedandpacked(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 assection/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.- When a real layout effect is needed,
alignedcan be rewritten as the C23_Alignas(N);packedhas 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 barepack()reset all follow the clang semantics and are observable viasizeof/_Alignof/offsetof) — the two spellings are interchangeable; the only difference is their shape:packedis a type-level binding (written on a type or a field) while#pragma packis an alignment cap over a lexical scope (effective from the pragma onward, restored bypop).__declspec(...)(the MSVC extension) is out of scope for this extension and not supported; use[[lib("X")]]for library ownership.- The rare
alignedforms (barealignedwith no argument,aligned(_Alignof(T)),aligned(type)) are downgraded to a light-warning ignore in this batch.
Current boundaries (compiler implementation status)
packedimplementation 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 packreally changes the layout too, since V0.5.0 —pack(N),pack(push, N)/pack(push)/pack(pop),pack(0)and a barepack()reset all follow the clang semantics. Four boundaries: (1) alignment cap: a member’s effective alignment ismin(natural alignment, N), i.e. pack compresses only the natural alignment, never an explicitly declared one (_Alignas, type-levelaligned), andpack(16)never raises alignment; (2) scope stack:push/poprestore one another, and apopon an empty stack warns and is ignored; (3) fixed at the definition point: a record takes the cap in effect where itsstruct/unionis defined, so a laterpopdoes 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 : 4still occupies 4 bytes), and pack only compresses the unit’s placement alignment tomin(natural, N)(pack(1)is equivalent topacked); a zero-width:0merely 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 underpack(2), 8/4 underpack(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 quotedpush, "name"is ignored as clang does.packedwith bit-fields and#pragma pack(1)with bit-fields are equivalent spellings.[[lib("X")]]lowers to a/DEFAULTLIBlinker directive in the COFF.drectvesection, 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 astruct/uniontype 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 toWinMainCRTStartupforWinMain, otherwise pinned tomainCRTStartup. It is valid only for Windows/COFF targets; the wide variantwWinMainis 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:
| Spelling | Equivalent type |
|---|---|
char / signed char / unsigned char | distinct types (char and signed char share width 1) |
short / short int / signed short / unsigned short | short / unsigned short |
int / signed / signed int / unsigned | int / unsigned int |
long / long int / signed long | long |
long long / long long int / unsigned long long | long long / unsigned long long |
_Bool / bool | the same type (bool is the spelling Co recommends) |
Qualifiers: const, volatile, restrict, _Atomic.
Widths and alignment
| Type | .c / .h | .co |
|---|---|---|
_Bool / bool | 1 / 1 | 1 / 1 |
char, signed char, unsigned char | 1 / 1 | 1 / 1 |
short, unsigned short | 2 / 2 | 2 / 2 |
int, unsigned int | 4 / 4 | 4 / 4 |
long, unsigned long | 4 / 4 | 8 / 8 |
long long, unsigned long long | 8 / 8 | 8 / 8 |
float | 4 / 4 | 4 / 4 |
double, long double | 8 / 8 | 8 / 8 |
wchar_t | 2 / 2 | 2 / 2 |
char8_t | 1 / 1 | 1 / 1 |
char16_t | 2 / 2 | 2 / 2 |
char32_t | 4 / 4 | 4 / 4 |
Any pointer, void* | 8 / 8 | 8 / 8 |
enum | 4 / 4 | 4 / 4 |
size_t, ptrdiff_t, intptr_t | 8 / 8 | 8 / 8 |
_BitInt(N) | ceil(N/8) / see below | same 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.
charis signed (char c = -1; printf("%d", c)prints-1), matching the MSVC / clang default on Windows. Writeunsigned charexplicitly when you need unsigned semantics.- Unsigned arithmetic wraps modulo the type width:
unsigned v = 0u - 1u;yields4294967295. - Signed overflow remains undefined behaviour; the language makes no saturation or wrap-around promise.
<stdint.h>givesint8_t…int64_t/uint64_tat the widths listed above;<stddef.h>givessize_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 doubleandunsigned long doubleare all rejected with a diagnostic such as'float' cannot be signed or unsigned; diagnostics spelllong doubleasdouble. - Floating literals take only the four suffixes
f/F/l/L, and upper and lower case must not be mixed (1.0lFis rejected).1.0dis 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._Alignofis 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 + 27on_BitInt(7)yields-1). - Mixed with
intthe result isint(the integer rank of_BitInt(N)is belowint). - For 128-bit integers write
_BitInt(128);__int128is 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 parameterint 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 wheresizeofis evaluated (consistent with ISO C): afterint n = 5; int a[n];, changingnto 9 makessizeof(a)yield 36. The array object does not grow withn; accessing past the original extent oncenis larger remains undefined behaviour. - Flexible array members (
char data[];) are covered by the “struct / union / enum” chapter.
Type aliases and inference
typedefbehaves as in ISO C and works for function pointers, arrays and structs; atypedefname 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 oftypeofis a type name, so it can be written directly insidesizeof(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;isint,auto p = &v;is a pointer,auto n = 3.5;isdouble, andauto f = 2.0f;keepsfloat(no default promotion). The formauto *p = &v;, which puts*into the declarator afterauto, is not supported today — write pointers asauto 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 |
|---|---|---|
1 | int (4) | int (4) |
1u | unsigned int (4) | unsigned int (4) |
1L / 1l | long (4) | long long (8) |
1UL | unsigned long (4) | unsigned long long (8) |
1LL / 1ULL | long long / unsigned long long (8) | same as left |
3000000000, 0xffffffff, 0x100000000 | 8 / 4 / 8 | same as left |
1wb / 1ub | exact-width _BitInt literal (1) | same as left |
Key points:
- An unsuffixed decimal that exceeds
intpromotes tolong(in.c4 bytes cannot hold it, so it skips tolong long); hencesizeof(3000000000) == 8. - Octal and hexadecimal try the unsigned candidates first, hence
sizeof(0xffffffff) == 4(unsigned int). - In the
.codialectlongandlong longare both 64-bit, so after de-duplicating the candidate sequence1Land1ULland on 64 bits directly. - Floating literals default to
double:1.0,.5and1.0Lare all 8 bytes;1.0f/1.0Farefloat. - The type of a character constant
'a'isint(sizeof('a') == 4); the prefixed forms areL'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 truncated1wand0x1ware rejected as invalid suffixes (invalid suffix 'w' on integer constant) rather than passing as an ordinaryint. Integer suffixes likewise require consistent case pairing:1lLand1wBare rejected, while1ll,1llu,1uwband1UWBare accepted. - The string prefixes
u8"…",u"…",U"…"andL"…"havechar8_t,char16_t,char32_tandwchar_telements 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/shortare promoted tointbefore arithmetic (intwhen it can hold all values, otherwiseunsigned int). Hence(char)100 + (char)100gives200andshort a = 30000; a + agives60000, neither overflowing. - Usual arithmetic conversions: on the integer side the wider type wins, and at equal width the unsigned side dominates —
unsigned + intisunsigned int,int + long longislong long; on the floating side mixingfloatwithdoubleyieldsdouble. - Explicit casts
(T)etruncate the value:(char)300gives44,(unsigned char)-1gives255; float-to-integer conversion truncates toward zero:(float)3.99gives3,(double)-2.7gives-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;
_Genericdispatches on the exact type, andbool/_Bool, orlong/long longinside.co, cannot be listed together because they are the same type.
sizeof, _Alignof and _Alignas
sizeofapplies to both types and expressions; applied to an arithmetic expression involving variables, the result is computed from the expression’s actual type: withdouble d; float f;,sizeof(d + d),sizeof(-d),sizeof(1 + d)andsizeof(d / f)all yield8,sizeof(f + f)yields4, andsizeof(c + c)(withchar c;, after integer promotion) yields4.- Applied to a struct,
sizeofreturns the total width including padding, and a flexible array member contributes 0; applied to a string it includes the\0. sizeof(void)yields 1 andsizeof(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}yields4,sizeof (double){0}yields8,sizeof (int[3]){0}yields12. When the parentheses hold a type name, the width still comes from the type, sosizeof (int) - 1issizeof(int) - 1(yields3), 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 dand_Alignof(d + 1)both yield the alignment of the operand’s type. Without parentheses it binds as a unary expression, so_Alignof d + 1is(_Alignof d) + 1(yields9). The spellings_Alignof/__alignof__/alignofare equivalent._Alignas(N)may be used on variables and struct members; the effective alignment is “the greater of natural alignment andN”:_Alignas(32) char buf[8];placesbufon a 32-byte boundary, andstruct { char c; _Alignas(16) int i; };hassizeof32.__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/.COfiles,long/unsigned longare always 8 bytes (as wide aslong long); in.h,.cand every other source file they stay native to the target (4 on Windows, 8 on Linux). Combined spellings widen too:long intandsigned longare also 8 bytes in.co. - The decision is made per source file of each declaration itself, not per “whole translation unit”: when a
.cofile#includes a.h, thelongin that header is still 4 bytes. Consequently the layout of a struct in a shared header is byte-for-byte identical on the.coand.csides — a single header never yields two differentsizeofvalues in the two kinds of source. longandLliterals produced by macro expansion follow the dialect of the use site: with#define BIG 0x100000000Lin a shared header, expanding it inside a.cofile computes in 64 bits and does not falsely report overflow.- Two writing disciplines derived from the 64-bit
longin.co:- Always write explicit widths when calling external (C) interfaces: if the callee returns 32 bits (Win32
DWORD/LONG), writeint/unsigned int; writelongorlong longonly when it truly returns 64 bits. The language provides no “reject external declarations containinglong” check — the compiler cannot see the real external signature and has no authority to judge correctness. - Inside
.co,longandlong longare the same type, so_Generic(x, long: 1, long long: 2)fails as a duplicate association; diagnostics may spell a.colongaslong long.
- Always write explicit widths when calling external (C) interfaces: if the callee returns 32 bits (Win32
- Where a value must stay consistent across
.coand.c, preferint32_t/int64_toutright.
Compatibility notice (regarding
long): in a.cofile,printf("%ld", v)passes 8 bytes while%ldreads only 4; the language performs no format-string checking, so use%lldor aPRId64-style spelling instead. Also,#include <limits.h>inside a.cofile still yields the 4-byteLONG_MAX(2147483647) — test the range of a 64-bitlongagainstINT64_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/_Imaginaryand the2.0iimaginary literal are not implemented (writing_Complexis diagnosed directly).__int128is not a spelling of this language; use_BitInt(128).long doublehas no extended precision — equivalent todouble.- The
volatile/restrict/_Atomicspecifiers do not reach code generation; they only affect type spelling and compatibility. auto *p = &v;is not supported (the*-declarator form followingauto); writeauto p = &v;.- Bare tags as types (
Point p;) are enabled only in.co; in.cyou still must writestruct 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 producesGNU 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 producesGNU 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).
| Element | Meaning |
|---|---|
TAG | Tag name; usable as a type identifier within the TU (bare-tag form, .co only) |
public | Cross-module visibility gate; without it the type stays module-internal and cannot be import-ed |
| member-declaration | Order in source equals layout order (subject to ISO C alignment rules except within a bit-field run) |
: bit-width | Bit field; width must be an integer constant not exceeding the underlying type’s width |
| anonymous member | Inline 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
| struct | class | |
|---|---|---|
| Kind | value type | reference type |
| Contents | member variables only | fields + methods + ctor/dtor + static members |
| Storage | stack value / heap handle | heap (class is always heap-allocated) |
| Reclamation | follows scope | Co 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 ofPointalso work at the call site (.coonly). sizeofyields the total byte size including internal padding, and includes any bytes occupied by anonymous members of the host. The flexible-array portion contributes 0.sizeofmay 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.sizeofapplied 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/enumtags 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
.cfiles —Point p;still reportsuse of undeclared identifier 'Point'and you must writestruct 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/uniontag that has only a forward declaration (no body) is allocated by value — a global or local variable definition, astructfield, 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->xmember access) andexterndeclarations 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,.core-parses it as a declaration. This is the same class of ambiguity as existingtypedefnames 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):
| struct | class | |
|---|---|---|
| Kind | value type | reference type |
| Contents | member variables only | member variables + methods + constructor/destructor + static members |
| Storage | stack value / heap handle | heap (class is only ever created on the heap) |
| Reclamation | follows scope | managed automatically by Co; manual release is normally not needed |
| Role | C-style data aggregate | encapsulation 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
thisand 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(). Thestatichere modifies class members only; it is not the file-scopestaticof C (which restricts a symbol to a single translation unit). Module-internal visibility in Co is expressed by omittingpublic(see the “Module” chapter). - Accessibility: a member/method is exposed based on
public— one that is not markedpublic(or is explicitly markedprivate, which is exactly equivalent at this level) is visible only inside the class; only those explicitly markedpublicare visible from outside. At the member/method level,public/privatedo not further restrict access between regions inside the class; the only place in Co that actually enforces an access restriction is theget/setaccessors 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 at0(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 bareget;/set;), the other accessor may be an explicit body that reads/writes that backing field directly via the contextual keywordfield— e.g.public int score { get; set { field = value < 0 ? 0 : value; } }.fieldis a contextual keyword, not reserved: it means the backing field only inside property accessors and is an ordinary identifier elsewhere.fieldis 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 barefieldin an accessor body still means the backing field; writethis.fieldto reach that member.
-
Read-only / write-only: giving only
getmakes it read-only — writing reportsproperty '…' is read-only (no setter); giving onlysetmakes it write-only — reading reportsproperty '…' is write-only (no getter). -
Compound assignment / increment-decrement:
obj.p += xexpands to “get, compute, set”;obj.p++/++obj.p/obj.p--/--obj.pdispatch the same way (the postfix form yields the old value before the update, the prefix form the new value). Both require the property to havegetandsetpresent 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.pis rejected:cannot take address of property 'p'. -
Per-accessor visibility (orthogonal to the property’s overall
public): each accessor may be individually prefixed withpublicorprivate; the default ispublic. An accessor markedprivatecan 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
privateset: writingobj.p = xfrom outside reportssetter of property 'p' is private, so the property looks read-only to outsiders; - a
privateget: readingobj.pfrom outside (including compound assignment and increment/decrement) reportsgetter of property 'p' is private, so the property looks write-only to outsiders.
This differs from the rule that “
privateat the module/member level is just an explicit spelling of omittingpublicand adds no restriction”—privateon a property accessor does enforce a real access restriction; it is the only place in Co’s visibility rules that carries enforcement. - a
-
Across modules: after importing another module’s
public class, its properties and their per-accessorpublic/privatebehave 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
deleteto 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
classhandle,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); explicitdeleteis available; apublic classbrought in viaimportcan 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(.cosource merge): one.cofile is one module,publicis 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 accessm.f()/m.xis enabled, and DLL / WinMain top-level-init carriers have landed. Using.obj/.dll/.soas 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
publicis 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 separateexport.privatemay appear anywhere as an explicit spelling of omittingpublic— its export and cross-module meaning are identical to omittingpublicand add no further visibility change. The only place in Co that actually enforces an access restriction is theget/setaccessors of a class property (see the “class” chapter).- A definition without
publicis visible only inside its module; only apublicdefinition is externally visible and importable. publicmay modify top-level functions, global variables, andstruct/union/enumtypes (cross-module type visibility has been available since 0.3.0/0.3.1), as well as file-scopetypedef(public typedef int MyInt;, part of the export surface since V0.4.1.40; a non-publictypedefis not exported);publiconclassand its members has been available since V0.4.0; apublic classfrom an imported module can benew-ed and its instance/static members, fields and properties used from the consuming module (cross-module consumption confirmed working since P391).- Non-
publicimported symbols are forced toInternalLinkageduring 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:
- 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). - 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). - Qualified type names as the escape hatch: write
a.Leaf/b.Leaf(ais theasalias, 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:
| Form | Description | Status |
|---|---|---|
.co | Source-file module, the most direct form | Implemented since V0.3.0 |
.obj | Compiled object file (-c output) | Deferred to later milestones |
.dll / .so | Native dynamic library | Deferred to later milestones |
Why an
.obj/.dllmodule is not “ready to use”:importneeds compile-time declaration information (function prototypes, type definitions, which names are externally visible), whereas an.obj/.dllis 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):
| Artifact | Carrier | Behavior |
|---|---|---|
| Console exe | synthesized main | calls each module’s initializer in topological order, then runs the main source’s top-level statements |
GUI exe (WinMain entry) | synthesized WinMain wrapper | the 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 DllMain | runs 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:
publiccontrols cross-module visibility — omitting it means “module-internal”, adding it makes a symbol importable;statickeeps its C meaning — internal linkage within its own translation unit, orthogonal topublic(static public/public staticin either order are legal; the symbol is still internal to the TU despite the export mark);- In the target specification,
staticis only a class static-member modifier (landed since V0.4.0class).
Not yet finalized
Deferred to later milestones:
- The declaration-metadata carrier that lets
.obj/.dll/.sobecome 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
.cofile = 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
structtypes 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 batchpublicdoes not change linkage (non-publicsymbols remainExternalLinkageby default, but non-publicimported symbols are stripped toInternalLinkageby codegen).static publicin either order is legal; semantics match P211.- Dynamic-library artifacts: there is no
-sharedoption, but the compiler switches between DLL and exe link modes automatically from the-ooutput extension. Naming the output*.dllproduces an export-table-bearing dynamic library (an import library*.libis generated alongside, verified on Windows). - Multi-file programs: compose several
.cosources withimport(available since V0.3.0). The single.objfrom-cis 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
.coconsumption. - Cross-module type references: a
public struct/union/enumimported from a module is usable as a value type (member access, address-of for passing, andsizeofall 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
publictag → an unconditional warning on the definition side; a host bare-name reference is an error (switch to the qualified type namemod.Tag); qualified type names work in declarations, thestructkeyword form, casts,sizeof/_Alignof/typeof, andnew, withstruct/union/enum/classhandled 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 intfrom an imported module is usable in the consumer as a read-only value, an array dimension, or aswitchcaselabel (since V0.3.1; theWM_*series inwinapi.cois exactly this use).
import (Module Import)
As of V0.3.0,
importis implemented for consuming.cosource-file modules. Using.obj/.dll/.soas importable modules is deferred to later milestones.Two hard limits — statement location and target: ① the
importstatement itself may only be written in.co/.COsource files; in.cor any other source file it is an error (see “Who may writeimport”); ② the import target may only be a.co/.COmodule —.c/.hare permanently rejected and.bcis 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];
| Element | Meaning |
|---|---|
name | A specific symbol to import (must be marked public in the source module) |
name as alias | A 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_name | Simplified identifier (no quotes, no extension, no separators); resolved only in the same directory |
ModAlias | A 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"ormodule_name:- String literal: allows cross-directory (relative or absolute) paths; the extension may be omitted (
.cois auto-appended when missing). - Simplified identifier: equivalent to
from "<name>.co", resolved in the importer’s directory.
- String literal: allows cross-directory (relative or absolute) paths; the extension may be omitted (
- 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:
importin a.cfile: 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.cocontainsimport, that is an error too, and the diagnostic points at the line and column inside that header — a.his always a C-surface file, never relaxed because a.coincludes it. - A pure C translation unit (
.c) has only#includefor reaching declarations across files, and a.ccannot consume any.comodule (includingwinapi.co).
Import Target Suffix Whitelist
The import target may only be .co/.CO:
| Target spelling | Status | Diagnostic / 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 consumption | binary library import (.dll/.lib/.so) is not supported yet |
"mod.c" / "mod.h" | ❌ permanently rejected | must be a .co/.bc module; C source files and headers cannot be imported (use #include) |
other suffixes (e.g. .txt, .obj) | ❌ rejected | must 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 Configwith a different layout, and eachsizeofuses 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>’sprintf) do not enter the module’s export surface. A host that also#include <stdio.h>has itsprintfunconflicted with the module’s — no more “import non-public symbol” error. - Macros are never exported (either direction):
#defineis 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, reportsuse of undeclared identifier. Function-like macros are more insidious: a call form such asXM_ADD(2, 3)is let through at compile time by the deliberately retained C89 implicit function declaration and only fails at link time withundefined symbol: XM_ADD(object-likeXM_MACROis 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
publicis the sole cross-module visibility gate: definitions withoutpublicare module-internal and cannot be reached by anyimport.- Named-import of a non-
publicsymbol: compile-time errorcannot import non-public symbol. - Non-
publicsymbols in a module reached viaimport *: silently skipped — only thepublicsurface is imported. - Qualified access
ModAlias.xhitting a missing or non-publicname in the module: errorno public symbol 'x' in module 'ModAlias'; if that name is a type in the module (a non-publicstruct/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-
publicsymbols: 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/enumkeyword and writingLeaf l;directly; - Compile-time constants: as array dimensions and
switchcaselabels.
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
publica 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 };andint g = p.GREEN;(including file-scope andstaticinitializers) all fold to the same integer constant.Still not available: bare enumeration constants do not cross modules (writing
GREENinmain.coafter theimportstill reportsuse of undeclared identifier) — for a cross-module integer constant usepublic 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
.cohas top-level statements (or a*.dll/WinMaincarrier 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;) andsizeofdo 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, chainedarr + 1 + 1and the string-literal base"abc" + 1all step by the element size (arr + 1advances bysizeof(element);&arr + 1advances by the whole array size) — this family used to compile yet fold tonull, crashing on the first runtime dereference; - Pointer targets are covered too (since V0.4.1.49): in
int *o = &M; int *p = o;theois a loaded non-constglobal, clang-std=c23rejects it, and colang now rejects it instead of silently folding to a null pointer (the compound formo + 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)&Kand{(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 loadedexterndeclaration used as an initializer, and a block-scopestatic 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 memberuu.cand{oo.buf, oa[1].buf}in an aggregate member position no longer fold tonull; 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;andint *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 + 2steps 1,oo.m[0] + 2steps 4). A chain that still contains one load (the arrowop->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.ayields the member gap — and the same batch curesint 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 + 1steps 1 byte,(short *)arr + 3steps 2,(void *)arr + 1steps 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 typeson 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 twovoid *operands used to crash the compiler (0xC0000005) and is now fixed, yielding a value with GNU’s byte-sized step (vp - vp2gives -12; note thatvoid *↔ object pointer remains an incompatible pair and is rejected as clang does); and pointer spellings in diagnostics now match clang (int (*)[4]instead ofint[4] *,int **instead ofint * *,unsigned char *instead ofchar *). Since V0.4.1.63 the&functionfallback is closed:&functionnow resolves to the real function prototype (&fgivesint (*)(void)), and the diagnostics align with clang accordingly — the difference formlong 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 tovoid *and were then judged compatible, is now reported; and the assignment form (int (*p)(void) = &g;), previously skipped silently because one side wasvoid *, 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); C23auto pf = f;/auto pa = arr;derive a function pointer / element pointer via the lvalue conversion, and the same batch cures the regression that falsely rejectedauto 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 — initializerincompatible 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), assignmentassigning to 'long' from 'int[4]'(anchored at=), argumentpassing 'int[4]' to parameter of type 'long'(source first); the reverse direction reportsincompatible 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;yieldsinitializing '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 ofbool 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 crash0xC0000005) and is rejected as well. Since V0.4.1.76 arithmetic and subscripting on avoid *follow GNU semantics with a 1-byte step: the statement formvoid *vp; vp[1];no longer crashes colang at compile time (it used to give0xC0000005; clang only warns with-Wunused-value),vp + 1/1 + vp/vp - 1/vp++/vp += 1are no longer falsely rejected withGEP into unsized type(a 1-byte step, the same rule as(void *)arr + 1andvoid * - void *), andsizeof(void)/sizeof(vp[1])are 1; reading avoidelement loads no memory (a zero placeholder is produced), so a nullvpis 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]andvf()[0]all reportsubscripted 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-declaredenumstays 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 asGEP into unsized type, and the enclosing shell reported an unrelated diagnostic first). Since V0.4.1.84, using avoidvalue 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 applyingsizeof/_Alignofto 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 thesizeofkeyword, 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 isinvalid application of 'sizeof' to an incomplete type 'struct I'(_Alignofprintsalignofeven when spelled_Alignof; typedef forms carry the(aka 'struct I')alias). A forward-declaredenum(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 thesizeof(completeness means “some definition exists in the TU”) and the dimension positionint 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 initializerstruct I *gq = gp + 1;) is on the sema rejection surface as well, matching clang line, wording and column: the wording isarithmetic 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, soint 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 typesis reported. Two known gaps remain:1 - ipbelongs to the separateinvalid operands to binary expressionfamily (still backed by the codegenGEP into unsized typefallback), 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 typedefis exported: writingt.Hiddenfor a non-publicone reportsno public type 'Hidden' in module 't'. - Fully on par with qualified type names: declarations, parameters, return types, pointers/arrays,
sizeof, casts(t.MyInt)xand 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) reportspublic 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
typedefwins (the bare name binds to the host), whilet.Xstill 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 withas ModAlias.
- If the filename is not a valid identifier (contains
- 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 = vbehaves like assigning a local variable; the only exception is writing aconstglobal (m.constGlobal = v), rejected withread-only variable is not assignable. - Qualified access only reaches
publicmembers; non-publicalways errorsno 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):
- Explicit named import vs a local of the same name → error (two explicit sources for one bare name).
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 thepublicsurface; non-publicis silently excluded.- Two wildcard modules share a name → the bare name is ambiguous and disabled (a reference reports
identifier not imported-style), butm1.name/m2.nameare each accessible via their qualifier and bind to their own definition. - Default qualifier = filename stem, overridable by
as ModAlias; a stem that is not a valid identifier requires an explicit alias. - Two explicit named imports of the same name from different modules → error.
- Minimal export surface: a module’s
publicacts as a visibility gate when merged into the host; for exe outputs it is not individually placed in a DLL export table. - Functions and globals follow the same rules:
m.fandm.xshare the resolution / shadowing / ambiguity trio. - Qualified write parity: there is no “cross-module read-only” gate;
m.x = vmatches a local write (onlyconstglobal writes are intercepted, see above). - 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 namem.Tagbinds 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
getwithout overwriting one another — at link time they coexist under synthesized symbol names (__<module-stem>__<name>), and each module’s internal call plusm1.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
importlines in the main source has no effect on this order. mainof a non-main module is not a load hook: if a module definesmain, 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
.coconsumption pipeline (lexing / parsing / loading / per-module closure analysis / merging / visibility enforcement / linkage strip / entry-model integration); - Both named and
*forms;import … as ModAliasenables qualified access; - Module-alias qualified access
m.f()/m.f/m.x/m.x = v(with local write parity andconstglobal write interception); - Independent module closures: per-module type/symbol isolation, same-name different-layout
structtypes never hijack each other; - Ambient cut-off: environment symbols brought in by a module’s
#includedo 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-
publicimported symbols are forced toInternalLinkageduring codegen; - Cross-module
public struct/union/enumtype 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
publicstruct/union/enumfrom 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 /structkeyword form / casts /sizeof/_Alignof/typeof/new), withstruct/union/enum/classhandled 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 qualifiedtypedef(a.MyInt, onlypublic typedefexported) ship in the same batch; since V0.4.1.47 qualified enum constants are also usable in compile-time constant positions (caselabels, array lengths,enuminitializers, global initializers), while bare enumeration constants still do not cross modules. - Cross-module compile-time constants: a
public const intfrom an imported module (e.g. theWM_*series inwinapi.co) is usable in the consumer as a plain read-only value, an array dimension, or aswitchcaselabel; globals that are notpublic const/ not enum constants (including a cross-modulepublic 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 loadedexterndeclarations and block-scopestaticinitializers 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 + 1steps 1,(void *)arr + 1steps 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 andenum *↔int *are still accepted); in the same batch a difference between twovoid *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&functionresolves to its real function prototype (&fgivesint (*)(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 avoid *use a 1-byte step with the statement formvp[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-declaredenumstill accepted); applyingsizeof/_Alignofto 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 - ipin the separate invalid-operands family, and file-scope forms whose record is defined after the arithmetic; - DLL / WinMain top-level-init carriers: producing
-o *.dllsynthesizes aDllMainthat runs each module’s top-level initialization underDLL_PROCESS_ATTACH(a user-authoredDllMainis renamed and forwarded); under a GUI-exeWinMainentry, top-level statements and runtime-initialized globals are carried by a synthesizedWinMainwrapper (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/.objas 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
| Option | Description |
|---|---|
-h, --help | Show usage and the option list |
-v, --version | Show the compiler version (four segments), the LLVM version used, and the target platform |
-E | Preprocess only; send the expanded token listing to standard output |
-c | Compile 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-context | Do 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
| Action | Output | Default name when -o is omitted |
|---|---|---|
| Default (compile + link) | Executable | Windows: <source basename>.exe; other platforms: <source basename> |
-c | .obj object file | <source basename>.obj |
-E | Standard output | Always 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.
Header search
In order of decreasing priority:
- Directories given with
-Ion the command line; - The Co-provided standard header directory (
stdio.h,stdint.h,winapi.co, …), located automatically: the environment variableCOLANG_STDLIBis checked first (point it straight at the header directory); if unset, the compiler walks upward (at most 8 levels) from the directory containing thecolangexecutable and locates thatinclude/directory by the presence ofinclude/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).
| Target | Data model | long | void* | wchar_t | Key predefined macros |
|---|---|---|---|---|---|
| Windows x64 | LLP64 | 4 | 8 | 2 | _WIN32 _WIN64 _MSC_VER __LLP64__ |
| Linux x86_64 | LP64 | 8 | 8 | 4 | __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-gnuon 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
libcmtand 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 locatescrt1.o/crti.o/crtn.o,libc.aandlibgcc; you need the static library packages installed (Debian/Ubuntulibc6-dev). The search locations can be overridden with theCOLANG_CRT_DIR,COLANG_LINUX_SYSROOTandCOLANG_GCC_LIB_DIRenvironment variables. Statically linked executables are currently supported; dynamic PIE /.soare 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")]]: writeuser32, notuser32.lib,C:\libs\user32oruser32.dll; a.libsuffix is tolerated (it is never doubled into.lib.lib). - Windows: each name becomes
-defaultlib:user32.libon 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 reportscannot open file 'xxx.lib'. - Linux: each name becomes
-l<name>inside the static link library group.
Boundaries:
--libaffects the link step only; under-cit 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 externalrc.exeneeded.
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.icofile 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, …), plusVALUEtext underSTRINGFILEINFOandTRANSLATIONunderVARFILEINFO; - string tables via
STRINGTABLE(and itsSTRINGentries) — encoded asRT_STRINGfollowing rc.exe’s rules; multipleSTRINGTABLEblocks in the same language may be declared across the script and are merged into the same group; - accelerators via
ACCELERATORS— encoded asRT_ACCELERATORwith rc.exe’s per-entry 8-byte layout and its end-of-blockfVirt0x80 marker (reproduced for byte-for-byte parity); keys accept a quoted single character or aVK_*virtual-key name (the latter requiringVIRTKEY), the optionsVIRTKEY/NOINVERT/SHIFT/CONTROL/ALTaccumulate as bit flags, and the command must be a numeric id after macro expansion; - extended dialogs via
DIALOGEX— encoded asRT_DIALOGfollowing rc.exe’sDLGTEMPLATEEX/DLGITEMTEMPLATEEXlayout, byte-for-byte identical to rc.exe; the dialog header acceptsx,y,cx,cy[,helpID]and the optional clausesSTYLE/EXSTYLE(|-separated style expressions, which may use commonWS_*/DS_*/WS_EX_*style macros or numeric values),CAPTION,MENU,CLASS, andFONT pt,"face"[,weight[,italic[,charset]]](which automatically setsDS_SETFONT); controls includePUSHBUTTON/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 generalCONTROL; 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
LANGUAGEstatements.
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)--resourceis 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) / menusMENU— are not yet supported and produce a clear diagnostic;DIALOGEXstyles/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.cosource, 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-contextfalls 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
-halso 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
| Version | Theme | Status |
|---|---|---|
| V0.1.0 | C compiler | Released |
| V0.2.0 | Co entry model + public | Released |
| V0.3.0 | Linking | Released |
| V0.3.1 | Windows GUI & winapi.co | Released |
| V0.3.2 | Linux native ELF toolchain | Released |
| V0.4.0 | class | Released |
| V0.4.1 | Diagnostics conformance & winapi | Released |
| V0.6.0 | Complex core slice + stdlib headers + linker diagnostics | Released |
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,boolfollowing C++ semantics, attribute syntax, etc.). - Hand-made
colibstandard headers to avoid cross-ABI dependencies. - Passes the Fujitsu
c-testsuiteconformance test suite. - Layered compiler structure: lexer → preprocessor → parser → sema → LLVM codegen, producing a single
.bcthat is handed to an external linker.
V0.2.0 — Co entry model + public
- Top-level statements execute in source order; a user
mainis not required (the compiler synthesizes the entry). - Coexistence of a user-written
mainand the synthesized entry; top-levelreturn V;sets the process exit code. - The
publickeyword marks exported symbols;-o *.dll/-o *.soselects 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 emptyret 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(.cosource merge): syntaximport * | name [as alias], … from ("file" | module_name);; consumes.cosources only,publicbeing 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 formfrom aequalsfrom "a.co"(same directory only). - The compiler links on its own:
-cemits a COFF.obj, and the default action links the object into an executable — no dependency on an externalclang. -
-o <name>.dllproduces a Windows dynamic library: with an export table, and a.libimport 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
.objmerging,.dll/.libconsumption, static library output. -
importextended to consume.obj/.dll/.libas importable modules (bundling compile-time declaration metadata). - Module-alias-limited access:
m.f(),m.x. - Refinement of
DllMainsynthesis and top-level body triggering for DLL outputs. - User-visible command-line arguments
argv: delivered via route A (.cotop-level entry has built-inargc(int) +argv(char**), C-form and self-contained, iterated by theargccount withargv[argc]==NULL), decoupled from the array-with-length infrastructure;argvas a globally visible, self-length-carrying string-array value type still awaits D37 (same batch asstring/general arrays).
V0.3.1 — Windows GUI & winapi.co
- Windows GUI subsystem and
WinMainentry:[[subsystem("windows")]]or definingWinMainswitches the artifact to a console-less GUI program;WinMainis mutually exclusive with top-level bare statements. winapi.coreplaceswindows.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).constconsistency: read-only enforcement (diagnostics matching clang);public const intvalues flow across modules into array dimensions andswitchcaselabels, 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,
unionhosts, mask-merged bit-field initialization, DFS continuation),sizeof/_Alignofin constant contexts, universal character names (\uXXXX/\UXXXXXXXX) in identifiers and literals, prefixed character constant typing,_Alignascontext constraints and cross-declaration consistency,static_assertin more scopes. - Diagnostics quality:
typedefalias 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-Ineeded). - 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
.cosources astruct/union/enummay be used as a type without its keyword (Point p;), including apublictag of an imported module. - Release version strings extended to four segments
MAJOR.MINOR.PATCH.Build(the fourth is a build counter, shown by-vand 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::elfstatically links the local glibc/libgcc into a native ELF executable (no external linker);crt1.o/libc.a/libm.a/libgccare 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
.rcresource compiler and the--resourceembedding channel (byte-for-byte alignment with rc.exe); the per-module compilation model promoted (independent closure + same-name routing + qualified access);wchar_t/wint_tmade target-aware across the chain; the synthesisedDllMaincarrier for DLLs; const diagnostics aligned with clang. - New default settings header
include/colang.hpreloaded automatically. - Follow-ups (long tail):
.soshared objects, dynamic PIE, x86-64 SysV ABI edge cases, ELF mapping ofwinapi.co, glibc audit of all stdlib headers.
V0.4.0 — class
- Reference type
classwithnewinstantiation andthismember access. - Four lifecycle protocols:
__new__/__retain__/__release__/__delete__. - Automatic reference counting and heap-object reclamation; out-of-scope auto-free.
publicextended 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 (
classhandles,struct/union/array embedded by value; parameters borrow, members are owned by the host); thedeletestatement for forced destruction and cycle breaking; correct release ongoto/break/continuepath terminations. - Follow-ups (long tail): inheritance and virtual functions; cross-module consumption of a
public classfrom animported module; the class form under multi-obj (--per-module); automatic cycle breaking (currently done withdelete).
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-contextdisables it. - CLI and source-surface tightening: new
-l/--libto specify external libraries;[[lib]]andclassdefinitions restricted to.cosources (rejected in.c/.h). - Co-layer robustness: fixed the degradation/crash when using a cross-module
public structby value inside animported module. winapi.cocontinues 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 _Complexcore slice:+ - * /arithmetic,== !=comparison, the constantI(_Complex_I), and the<complex.h>accessorscreal/cimag/conj/cabs/carg/projection(withfvariants). Transcendental functions such ascexp/clog/csqrtand the standalone_Imaginarytype are not yet supported. - Link-time
undefined symboldiagnostics now report the real call-site file, line and column. <threads.h>adds the C11 timed functionsthrd_sleep/mtx_timedlock/cnd_timedwait, and now includes<time.h>sostruct timespecis visible.- Fixed duplicate
publicglobal declarations in one.comodule 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/wstringvalue 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:importcurrently consumes.cosources only; planned to consume.dll/.lib/.so/.abinaries directly (the production side is already in place). classinheritance / virtual functions / RTTI: on top of the deliveredclasscore, add single/multiple inheritance, virtual functions and runtime type information, with up- and down-casting.- Full
winapi.cocoverage: 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
classnow supports properties: a class member can be defined as a property via an accessor pair —int a { get { return _a; } set { _a = value; } }; readingobj.a/ writingobj.a = xuses the same syntax as an ordinary field and dispatches toget/setautomatically. Read-only (onlyget), write-only (onlyset) 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 keywordfieldreads/writes that backing storage directly (matching C# 14 style).obj.prop++/--(prefix / postfix) and compound assignmentobj.prop += xall expand correctly as “read, modify, write”; a property has no independent storage address, so taking its address (&obj.prop) is an error.- New
privatekeyword + accessor-level visibility:privateis explicit sugar (semantically equivalent to omittingpublic; cross-module visibility is still governed by the singlepublicgate) and may precede members / methods / properties at the top level, the class header, and inside the class body;publicandprivatetogether on one declaration is an error. Each property accessor can carry its own visibility (e.g.public int a { get; private set; }) — an accessor markedprivatemay 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
returna 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
classmethod 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, missingreturnin a non-voidfunction, 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 bareundefined symbolat 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: aunionwhose 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.cocontinues 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 fullwinerror.herror-code mirror).
V0.6.1
winapi.coconstants greatly expanded: Win32 constants grow from a few hundred to roughly 12,600, including a full mirror of thewinerror.herror codes (7416 entries, line-by-line against Windows SDK 10.0.26100.0shared\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.cofixes 18 mismatches with the SDK: 14 function prototypes’ return / parameter types (e.g.SetLastErrorreturnsvoid,CreateSemaphoreWreturnsHANDLE,GetAsyncKeyStatereturnsSHORT), 1 constant value (IDC_NO), and 3 struct layouts (LOGPENrewritten per SDK,MODULEENTRY32Wfield names,WSADATA.szSystemStatuslength); 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 themain/WinMainfunction; it can now be written as a standalone directive at the top level of a.cofile, so a Windows GUI program can be produced from the directive plusimportand top-level bare code — the “minimal Windows GUI example” in the docs (file-level[[subsystem("windows")]]+import * from winapi;+ bareMessageBoxA) now works. It takes effect only in the main module; the attribute in an imported module is ignored with a warning.winapi.cointernal restructure (transparent to users): the monolithicwinapi.cois split into an umbrella trio (winapi.co+ internal partswinapi_core.co/winapi_winerror.co) merged back via#includetext inclusion — existingimport … from "winapi.co"is unchanged and keeps working, with no user code needing modification.
V0.6.0
- C
_Complexsupport (core slice):.c/.conow support thefloat _Complex/double _Complextypes,+ - * /arithmetic,== !=comparison, the constantI(_Complex_I), and the<complex.h>accessorscreal/cimag/conj/cabs/carg/projection(withfvariants). This batch is a core slice: transcendental functions such ascexp/clog/csqrtand the standalone_Imaginarytype are not yet supported;int _Complexis 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 symbolpreviously always pointed at<obj>:1:1with 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_timedwaitare now provided; and<threads.h>now includes<time.h>, sostruct timespecis directly visible without the user including the header themselves.- Fix duplicate
publicglobal declarations in one module making consumers read the initial value: previously, declaring the samepublicglobal variable twice in one.comodule 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 - ptrpointer difference fixed to 64 bits: subtracting two pointers was truncated to a 32-bitint, so a span over 2 GiB came out negative or wrong; it now returns a 64-bit value like clang, andsizeof(p - q)is corrected from 4 to 8.- Referencing a
public structno longer crashes: when apublic structhad a member type not markedpublic, 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 apublic structshould still be markedpublic. math.hadds declarations forcopysign,nan,nextafterfand 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.hadds C23 floating-point feature macros: new macros such asFLT_DECIMAL_DIG,DBL_DECIMAL_DIG,FLT_EVAL_METHODandFLT_HAS_SUBNORM(9 in total) for feature detection.#ifnow 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 > -1tested false); this now matches clang and tests true.winapi.coconstants corrected: 6 wrong values fixed (among themSTD_INPUT_HANDLE/STD_OUTPUT_HANDLE/STD_ERROR_HANDLEwere misaligned, soGetStdHandle(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.coare now usable across modules: 36 aliases —DWORD/WORD/BYTE/BOOL/HANDLE/HWND/LPARAM/WNDPROCand the rest — were not markedpublic, so even afterimport * from winapi;they still produceduse of undeclared identifier(and variables declared with those aliases were cascaded into the same error). All 36 are nowpublic 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 atypedefor a tag with one of these names, they clash. - Calling a non-
publicfunction across modules is now a compile-time error: calling a function that another module defines with a body but did not markpublicused to compile fine and then fail at link time with a bareundefined symbol: X(no source position); it is now rejected at compile time withcannot import non-public symbol 'X'plus source context for the offending line. The rule covers only functions that have a body and are notpublic; non-publicpure 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 reporttoo 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 (itssetjmp.hprototype 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 parameterlessf()with arguments now reportstoo 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=c23decides. public typedef struct X Y;now has complete types inside non-root modules: after importing the module,sizeof(Y)/ a localY y;used to be falsely reported as incomplete, andp->amember access or anf(Y h)by-value parameter could even crash the compiler (0xC0000005, no diagnostic); usingY inner;as a struct value member failed only in LLVM verification. From this release the five alias forms are fully equivalent to thestruct Xtag form; genuinely incomplete types are still rejected in the front end with clang-matching diagnostics.
V0.5.2
math.hgains thelong doublemaths declarations (all 56 of the C standard family): thel-suffixed functions —asinhl/acoshl/atanhl/sqrtland the rest — had no declarations at all inmath.h. Following the C implicit-function-declaration rule, colang treated an undeclared function as returningint, 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 56l-suffixed declarations, each prototype taken verbatim from the Windows UCRT header (including the host-specific spellings:nexttowardl’s second parameter islong double,ilogblreturnsint,lrintl/lroundlreturnlong,llrintl/llroundlreturnlong long, andscalblnl’s second parameter islong). 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 deliverscomplex.h, which defines__STDC_NO_COMPLEX__per the C standard (honestly reporting that complex support is absent). colang still does not implement the_Complex/_Imaginarytypes, and this header deliberately does not defineI— definingIas a real number would let1.0 + 2.0 * Isilently evaluate to3.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/-Wextrawarnings added: new-Wunused-variable,-Wunused-function,-Wunused-but-set-variable,-Wswitch(an enumswitchthat does not cover all enumerators and has nodefault), 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_tunit widths, redefinition in the same scope, andfor/if/switchinit-statement scopes — are now all rejected with clang-matching wording and line/column positions. - Major
winapi.coexpansion: 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 viasizeof/offsetof.
V0.5.0
long/unsigned longin.cosources is now 8 bytes (Windows target);longandlong longare now the same type..c/.hare unchanged and still follow the target data model (4 bytes on Windows / 8 on Linux). Three migration consequences: ①longandlong longcan no longer both appear in one_Generic; ② taking the address of a.colongvariable and passing it to an API prototype declared withint/unsigned int(winapi.cofollows the SDK spellings and never useslong) is now rejected as incompatible pointer types; ③ printing a 64-bit integer requires%lld—%ldreads only 4 bytes and yields a wrong value.winapi.coconstants corrected and expanded (every one of the 509 constants in the section was re-verified numerically against Windows SDK 10.0.26100.0):SM_CXSCREEN78→0,SOMAXCONN-1→0x7FFFFFFF,FILE_NOTIFY_CHANGE_LAST_WRITE0x8→0x10,PATCOPY0x00F00062→0x00F00021— code using these four constants changes runtime behaviour, since it previously passed wrong values. Also addedFILE_NOTIFY_CHANGE_SIZE,SM_CYSCREEN,SM_XVIRTUALSCREEN,SM_YVIRTUALSCREEN,SM_CXVIRTUALSCREENandSM_CYVIRTUALSCREEN, so locally re-declared stand-in constants can go back to thewinapi.coones.- 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/unsignedon 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 thanunsigned long long(18446744073709551616,0xFFFFFFFFFFFFFFFFFFFF). Valid spellings are unaffected:1uwb/1UWB/0b1010wb,1.0f/1.0L,08.5/09e1and9223372036854775808(typedunsigned long long) are still accepted. winapi.cobatch XIII expansion and two return-type corrections: correctedSendMessageA’s return typeint→long long(SDK returns LRESULT, 8 bytes on x64; the old spelling truncated the high 32 bits of the return value) andRegisterClassA’s return typeshort→unsigned short(SDK returns ATOM=WORD; window-class atoms always land in 0xC000–0xFFFF and read as negative when taken asshort). Added theWNDCLASSWstruct, 18 prototypes (user32CreateMenu/GetMenu/SetMenu/GetSubMenu/EnableMenuItem/RegisterClassW/UnregisterClassW/RegisterHotKey/UnregisterHotKey/LoadStringW; kernel32CopyFileW/RemoveDirectoryW/GetFileSizeEx/FormatMessageW/LocalAlloc/LocalFree; gdi32GetTextMetricsW; comdlg32GetSaveFileNameW) 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 ofwinapi.codocuments 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 asptr(the correct Microsoft x64 “pass by reference” lowering).WindowFromPoint(struct POINT)behaviour is corrected;SetFilePointerEx(union LARGE_INTEGER)is added towinapi.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-contextdisables it. - CLI and source-surface tightening: new
-l/--libto specify external libraries;[[lib]]andclassdefinitions are restricted to.cosources (rejected in.c/.h). - Co-layer robustness: fixed the degradation/crash when using a cross-module
public structby value inside animported module. winapi.cocontinues 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
classreference type (heap-only + automatic reference counting): instantiation vianew, member access viathis, instance methods and static members viaC::m(); handles are released in reverse frame order when leaving scope, andbreak/continue/gotopath terminations release them correctly. - Member and parameter types opened up: primitives,
class,struct/union/arrays all work — astruct/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
deletestatement: 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 classin animported module cannot yet be consumed across modules; reference cycles are not broken automatically (usedelete). - Major
winapi.coexpansion: 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
.cosources astruct/union/enumvariable definition, parameter orsizeofmay drop the keyword (Point p;), and apublictag 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);-voutput 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
.rcsyntax, 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-gnuemits 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.varsupported. wchar_tfully 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 herepointing at the declaration site; new-Wdefault-const-initwarning (function-local const objects or those with const members without initializer). - DLL production: synthesised
DllMainentry carrier, top-level initialisation code driving,publicfunctions written into the export table. - Multiple fixes in integer literal type selection, bit-field masking, and dynamic CRT linking.
V0.3.1
- The
winapi.comodule:import … from "winapi.co"replaceswindows.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 definingWinMain) produces a console-less windowed program. - Co-layer enhancements:
public const int/public structetc. from an imported module can be used across modules directly; designated initializers support chained designators and anonymousunionmembers. - C compatibility: universal character names (
\uXXXX) in identifiers;u8/u/U/Lprefixed character constants;sizeof(string literal);static_assertin multiple scopes; the[[nodiscard]]/[[noreturn]]/[[deprecated]]attributes. - Diagnostics:
constread-only enforcement, up-front incomplete-type diagnostics and rejection of non-constantswitchcaselabels, 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:
-cemits a COFF.obj, and the default action links the object into an executable — no dependency on an externalclang. - Static CRT linked by default: the produced exe ships without requiring the VC runtime to be installed.
-o <name>.dllproduces a Windows dynamic library: with an export table, and a.libimport 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(.cosource merge) landed:- Syntax:
import * | name [as alias], … from ("file" | module_name) [as ModAlias];; - Consumes
.cosources only;publicis 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 ais accepted, equivalent tofrom "a.co"(same directory only).
- Syntax:
- Referencing a non-imported symbol from the main source is rejected; importing a non-
publicsymbol via named or*form is rejected. - Non-
publicimported symbols are forced toInternalLinkageduring 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,
publicfunctions, andimportsupport; - 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.