comptime compiler-API: Phase 1 foundation + Phase 2.1 weld plan
Introduce the welded comptime `compiler` library (`#library "compiler"` +
`abi(.zig) extern compiler`), per design/comptime-compiler-api.md, and unify
`callconv(...)` into the new `abi(...)` annotation.
abi(...) replaces callconv(...):
- New ABI enum { default, c, zig, pure }; `abi(.c|.zig|.pure)` parses in the
postfix slot before extern/export (and standalone). `kw_callconv` -> `kw_abi`.
- Migrated 52 sx files, the call-convention-mismatch diagnostic, and docs
(readme/specs) from `callconv(.c)` to `abi(.c)`.
Phase 1 — welded compiler library (parse -> registry -> validation -> bridge):
- `abi(.zig) extern compiler` parses on fn decls (carries abi/extern_lib) and
struct decls (StructDecl.abi/extern_lib).
- `#library "compiler"` is the comptime-only internal surface — never dlopen'd.
- src/ir/compiler_lib.zig: the binding registry (the safety boundary). `Field`
welded to StructInfo.Field with layout baked from the real Zig type
(@offsetOf/@sizeOf); `findType`/`findFn`. Welded structs are layout-validated
at registration (field set + total size) as a header checked against the impl.
- Host-call bridge: a `fn abi(.zig) extern compiler` dispatches under the
comptime interp to its registered Zig handler (intern/text_of round-trip),
never dlsym. IR Function.compiler_welded; validated in declareFunction.
- Comptime-only enforcement: a runtime call to a welded fn is a clean
build-gating error (emitCall), not an undefined-symbol link failure.
Phase 2.1 — byte-layout weld foundation:
- Decision: full byte-layout weld (sx struct laid out byte-identically to the
bound Zig type). Registered StructInfo (first non-natural / Zig-reordered
layout). `computeWeldPlan` — pure offset-ordered element plan + padding +
sx-field->LLVM-element remap; unit-tested. Emit/interp wiring is the next
sub-step (2.2+, see current/CHECKPOINT-COMPILER-API.md).
Examples: 0625/0626 (welded struct + fn round-trip), 1183/1184/1185
(layout-mismatch, unexported-fn, runtime-call diagnostics).
This commit is contained in:
52
src/ast.zig
52
src/ast.zig
@@ -122,14 +122,26 @@ pub const Root = struct {
|
||||
decls: []const *Node,
|
||||
};
|
||||
|
||||
pub const CallingConvention = enum { default, c };
|
||||
/// ABI / calling-convention annotation written as the postfix `abi(.x)` form on a
|
||||
/// function declaration, function-type literal, or lambda. Subsumes the old
|
||||
/// `callconv(...)` spelling.
|
||||
/// - `.default` — no annotation: the ordinary sx-internal convention (implicit
|
||||
/// context, sx ABI). There is no surface spelling for `.default`; it is the
|
||||
/// value when `abi(...)` is absent.
|
||||
/// - `.c` — C ABI / cdecl, no implicit context (what `callconv(.c)` meant).
|
||||
/// - `.zig` — welded to the real internal Zig type/fn: layout follows the bound
|
||||
/// Zig type, functions dispatch over the comptime host-call bridge. The
|
||||
/// `compiler` library (`design/comptime-compiler-api.md`) binds via `abi(.zig)`.
|
||||
/// - `.pure` — a pure / naked function (inline asm body), no calling-convention
|
||||
/// prologue/epilogue.
|
||||
pub const ABI = enum { default, c, zig, pure };
|
||||
|
||||
/// Linkage modifier written in the postfix slot after `callconv(...)`:
|
||||
/// `name :: (sig) -> Ret [callconv(.x)] [extern | export] [;|{…}];`
|
||||
/// `extern` = import (external linkage, C ABI, no sx ctx — `extern`'s role);
|
||||
/// `export` = define + expose (body + external linkage + C ABI + no ctx).
|
||||
/// Both imply `callconv(.c)`. Variants carry a trailing `_` to dodge the Zig
|
||||
/// keywords. `.none` = no linkage modifier (the ordinary sx-internal decl).
|
||||
/// Linkage modifier written in the postfix slot before `abi(...)`:
|
||||
/// `name :: (sig) -> Ret [extern | export] [abi(.x)] [lib] [;|{…}];`
|
||||
/// `extern` = import (external linkage, no sx ctx — `extern`'s role);
|
||||
/// `export` = define + expose (body + external linkage + no ctx).
|
||||
/// Variants carry a trailing `_` to dodge the Zig keywords. `.none` = no linkage
|
||||
/// modifier (the ordinary sx-internal decl).
|
||||
pub const ExternExportModifier = enum { none, extern_, export_ };
|
||||
|
||||
pub const FnDecl = struct {
|
||||
@@ -139,10 +151,15 @@ pub const FnDecl = struct {
|
||||
body: *Node,
|
||||
type_params: []const StructTypeParam = &.{},
|
||||
is_arrow: bool = false,
|
||||
call_conv: CallingConvention = .default,
|
||||
/// Postfix linkage modifier (`extern`/`export`) written after the
|
||||
/// `callconv(...)` slot. `.none` for an ordinary sx-internal function.
|
||||
/// Parsed in Phase 0.1; not consumed by the fn-decl path until Phase 1.
|
||||
/// ABI / calling-convention annotation (`abi(.c)` / `abi(.zig)` / `abi(.pure)`)
|
||||
/// in the postfix slot after `extern`/`export`. `.default` = unannotated.
|
||||
/// `.zig` marks a function bound to the comptime `compiler` library — its
|
||||
/// signature is welded to the real internal Zig fn and it dispatches over the
|
||||
/// host-call bridge at comptime (consumed by the binding registry + host-call
|
||||
/// bridge in later phases).
|
||||
abi: ABI = .default,
|
||||
/// Postfix linkage modifier (`extern`/`export`) written before the `abi(...)`
|
||||
/// slot. `.none` for an ordinary sx-internal function.
|
||||
extern_export: ExternExportModifier = .none,
|
||||
/// Optional library reference + symbol-name override for an `extern`/`export`
|
||||
/// function, the optional library + symbol-name override. Both
|
||||
@@ -510,6 +527,15 @@ pub const StructDecl = struct {
|
||||
using_entries: []const UsingEntry = &.{},
|
||||
methods: []const *Node = &.{}, // fn_decl nodes for struct methods
|
||||
constants: []const *Node = &.{}, // const_decl nodes for struct-level constants
|
||||
/// ABI / layout annotation (`struct abi(.zig) extern <lib> { … }`). `.default`
|
||||
/// for an ordinary struct. `.zig` marks a layout-welded binding to the named
|
||||
/// `compiler` library's real Zig type — its field offsets are taken from the
|
||||
/// bound Zig type (`@offsetOf`) and asserted equal at compiler-build time.
|
||||
/// Parsed in Phase 1; consumed by the binding registry + layout engine later.
|
||||
abi: ABI = .default,
|
||||
/// The bound library handle for an `abi(.zig) extern <lib>` welded struct
|
||||
/// (e.g. `compiler`); null for an ordinary struct.
|
||||
extern_lib: ?[]const u8 = null,
|
||||
/// True when the declared NAME was a backtick raw identifier
|
||||
/// (`` `i2 :: struct { … } ``) — exempt from the reserved-type-name decl
|
||||
/// check. A bare reserved-name decl still errors.
|
||||
@@ -533,7 +559,7 @@ pub const Lambda = struct {
|
||||
return_type: ?*Node,
|
||||
body: *Node,
|
||||
type_params: []const StructTypeParam = &.{},
|
||||
call_conv: CallingConvention = .default,
|
||||
abi: ABI = .default,
|
||||
};
|
||||
|
||||
pub const TypeExpr = struct {
|
||||
@@ -805,7 +831,7 @@ pub const FunctionTypeExpr = struct {
|
||||
param_types: []const *Node,
|
||||
param_names: ?[]const ?[]const u8 = null, // optional documentation names
|
||||
return_type: ?*Node, // null = void return
|
||||
call_conv: CallingConvention = .default,
|
||||
abi: ABI = .default,
|
||||
};
|
||||
|
||||
pub const ClosureTypeExpr = struct {
|
||||
|
||||
@@ -29,12 +29,12 @@ pub const AbiLowering = struct {
|
||||
/// `is_extern_c_api` knob. When true, sx `string` / `[]T` slices
|
||||
/// collapse to `ptr` — the libc convention where the user writes
|
||||
/// `string` to mean `char *` and the length is dropped. When
|
||||
/// false (sx-internal `callconv(.c)` like block trampolines), the
|
||||
/// false (sx-internal `abi(.c)` like block trampolines), the
|
||||
/// full slice shape is preserved and goes through the general
|
||||
/// struct-coerce path (16-byte slice → `[2 x i64]`, lands in two
|
||||
/// registers on AArch64 — the true C ABI for a 16-byte
|
||||
/// aggregate). Without the split, sx-to-sx calls through a
|
||||
/// `(*Block, string) -> void callconv(.c)` fn-pointer mismatched
|
||||
/// `(*Block, string) -> void abi(.c)` fn-pointer mismatched
|
||||
/// the caller's `{ptr, i64}` value against the trampoline's
|
||||
/// collapsed `ptr` param.
|
||||
pub fn abiCoerceParamTypeEx(self: AbiLowering, ir_ty: TypeId, llvm_ty: c.LLVMTypeRef, is_extern_c_api: bool) c.LLVMTypeRef {
|
||||
|
||||
@@ -1118,6 +1118,23 @@ pub const Ops = struct {
|
||||
pub fn emitCall(self: Ops, instruction: *const Inst, call_op: Call) void {
|
||||
// Evaluate comptime functions at compile time
|
||||
const callee_func = &self.e.ir_mod.functions.items[call_op.callee.index()];
|
||||
|
||||
// Welded `compiler`-library functions are comptime-only — they have no
|
||||
// runtime symbol (the comptime interp dispatches them to a Zig handler).
|
||||
// A welded call inside a RUNTIME function is illegal; surface a clean
|
||||
// build-gating error instead of an undefined-symbol link failure. A
|
||||
// welded call inside a COMPTIME function (a `#run` / `::` initializer
|
||||
// wrapper, `is_comptime`) is fine — that body is interp-evaluated and its
|
||||
// LLVM emission is dead, so skip the gate there.
|
||||
const enclosing = &self.e.ir_mod.functions.items[self.e.current_func_idx];
|
||||
if (callee_func.compiler_welded and !enclosing.is_comptime) {
|
||||
const fname = self.e.ir_mod.types.getString(callee_func.name);
|
||||
std.debug.print("error: '{s}' is a comptime-only compiler-library function — it cannot be called at runtime (use it inside #run or a comptime '::')\n", .{fname});
|
||||
self.e.comptime_failed = true;
|
||||
self.e.mapRef(c.LLVMGetUndef(self.e.toLLVMType(instruction.ty)));
|
||||
return;
|
||||
}
|
||||
|
||||
if (callee_func.is_comptime and call_op.args.len == 0) {
|
||||
var interp_inst = Interpreter.init(self.e.ir_mod, self.e.alloc);
|
||||
interp_inst.build_config = &self.e.build_config;
|
||||
|
||||
177
src/ir/compiler_lib.test.zig
Normal file
177
src/ir/compiler_lib.test.zig
Normal file
@@ -0,0 +1,177 @@
|
||||
// Tests for the comptime `compiler` library's binding registry.
|
||||
|
||||
const std = @import("std");
|
||||
const compiler_lib = @import("compiler_lib.zig");
|
||||
const types = @import("types.zig");
|
||||
|
||||
// Lock: `findType("Field")` resolves to the welded `StructInfo.Field` type, and
|
||||
// its baked layout EQUALS the real Zig type's `@sizeOf`/`@alignOf`/`@offsetOf`.
|
||||
// This is the foundation the layout sub-step builds on — the welded record's
|
||||
// offsets come from the implementation, so they can't drift.
|
||||
test "compiler_lib: Field welds to StructInfo.Field's real layout" {
|
||||
const FieldZig = types.TypeInfo.StructInfo.Field;
|
||||
|
||||
const bt = compiler_lib.findType("Field") orelse return error.MissingBoundType;
|
||||
|
||||
try std.testing.expectEqualStrings("Field", bt.sx_name);
|
||||
try std.testing.expectEqual(@sizeOf(FieldZig), bt.size);
|
||||
try std.testing.expectEqual(@alignOf(FieldZig), bt.alignment);
|
||||
|
||||
// Two u32 fields, in declaration order.
|
||||
try std.testing.expectEqual(@as(usize, 2), bt.fields.len);
|
||||
|
||||
try std.testing.expectEqualStrings("name", bt.fields[0].name);
|
||||
try std.testing.expectEqual(@offsetOf(FieldZig, "name"), bt.fields[0].offset);
|
||||
try std.testing.expectEqual(@as(usize, 4), bt.fields[0].size);
|
||||
|
||||
try std.testing.expectEqualStrings("ty", bt.fields[1].name);
|
||||
try std.testing.expectEqual(@offsetOf(FieldZig, "ty"), bt.fields[1].offset);
|
||||
try std.testing.expectEqual(@as(usize, 4), bt.fields[1].size);
|
||||
|
||||
// Sanity: the concrete shape the design calls out — two u32s, 8 bytes.
|
||||
try std.testing.expectEqual(@as(usize, 8), bt.size);
|
||||
try std.testing.expectEqual(@as(usize, 0), bt.fields[0].offset);
|
||||
try std.testing.expectEqual(@as(usize, 4), bt.fields[1].offset);
|
||||
}
|
||||
|
||||
// Lock: a name NOT on the export list is unreachable — `findType` returns null
|
||||
// (the safety boundary; the welded-decl path falls through to a clean error,
|
||||
// never a silent default).
|
||||
test "compiler_lib: unexported name returns null" {
|
||||
try std.testing.expect(compiler_lib.findType("NotExported") == null);
|
||||
try std.testing.expect(compiler_lib.findType("") == null);
|
||||
}
|
||||
|
||||
// Lock: a faithful sx header for `Field` validates clean (the natural two-u32
|
||||
// layout matches the welded type).
|
||||
test "compiler_lib: validateStructLayout accepts a faithful Field header" {
|
||||
const bt = compiler_lib.findType("Field").?;
|
||||
const sx = [_]compiler_lib.SxField{
|
||||
.{ .name = "name", .size = 4 },
|
||||
.{ .name = "ty", .size = 4 },
|
||||
};
|
||||
try std.testing.expect(compiler_lib.validateStructLayout(bt, &sx, 8) == null);
|
||||
}
|
||||
|
||||
// Lock: every drift the assertion is meant to catch surfaces as the right
|
||||
// `LayoutMismatch` variant (field count / name / size / total), and the first
|
||||
// mismatch wins.
|
||||
test "compiler_lib: validateStructLayout flags each kind of drift" {
|
||||
const bt = compiler_lib.findType("Field").?;
|
||||
|
||||
// Wrong field count (one field instead of two).
|
||||
{
|
||||
const sx = [_]compiler_lib.SxField{.{ .name = "name", .size = 4 }};
|
||||
const m = compiler_lib.validateStructLayout(bt, &sx, 4).?;
|
||||
try std.testing.expect(m == .field_count);
|
||||
try std.testing.expectEqual(@as(usize, 2), m.field_count.expected);
|
||||
try std.testing.expectEqual(@as(usize, 1), m.field_count.got);
|
||||
}
|
||||
// Wrong field name (reorder / rename) at index 1.
|
||||
{
|
||||
const sx = [_]compiler_lib.SxField{
|
||||
.{ .name = "name", .size = 4 },
|
||||
.{ .name = "kind", .size = 4 },
|
||||
};
|
||||
const m = compiler_lib.validateStructLayout(bt, &sx, 8).?;
|
||||
try std.testing.expect(m == .field_name);
|
||||
try std.testing.expectEqual(@as(usize, 1), m.field_name.index);
|
||||
try std.testing.expectEqualStrings("ty", m.field_name.expected);
|
||||
try std.testing.expectEqualStrings("kind", m.field_name.got);
|
||||
}
|
||||
// Wrong field size (retype to an 8-byte field).
|
||||
{
|
||||
const sx = [_]compiler_lib.SxField{
|
||||
.{ .name = "name", .size = 4 },
|
||||
.{ .name = "ty", .size = 8 },
|
||||
};
|
||||
const m = compiler_lib.validateStructLayout(bt, &sx, 12).?;
|
||||
try std.testing.expect(m == .field_size);
|
||||
try std.testing.expectEqual(@as(usize, 1), m.field_size.index);
|
||||
try std.testing.expectEqual(@as(usize, 4), m.field_size.expected);
|
||||
try std.testing.expectEqual(@as(usize, 8), m.field_size.got);
|
||||
}
|
||||
// Right fields, wrong total (padding drift).
|
||||
{
|
||||
const sx = [_]compiler_lib.SxField{
|
||||
.{ .name = "name", .size = 4 },
|
||||
.{ .name = "ty", .size = 4 },
|
||||
};
|
||||
const m = compiler_lib.validateStructLayout(bt, &sx, 16).?;
|
||||
try std.testing.expect(m == .total_size);
|
||||
try std.testing.expectEqual(@as(usize, 8), m.total_size.expected);
|
||||
try std.testing.expectEqual(@as(usize, 16), m.total_size.got);
|
||||
}
|
||||
}
|
||||
|
||||
// Lock: `Field` (natural two-u32 layout) has the trivial weld plan — two field
|
||||
// elements in declaration order, no padding, identity remap.
|
||||
test "compiler_lib: weld plan for Field is the identity (no reorder, no pad)" {
|
||||
const alloc = std.testing.allocator;
|
||||
const bt = compiler_lib.findType("Field").?;
|
||||
var plan = try compiler_lib.computeWeldPlan(alloc, bt.fields, bt.size);
|
||||
defer plan.deinit(alloc);
|
||||
|
||||
try std.testing.expectEqual(@as(usize, 8), plan.total_size);
|
||||
try std.testing.expectEqual(@as(usize, 2), plan.elements.len);
|
||||
// Identity remap.
|
||||
try std.testing.expectEqual(@as(usize, 0), plan.sx_to_llvm[0]);
|
||||
try std.testing.expectEqual(@as(usize, 1), plan.sx_to_llvm[1]);
|
||||
// Both elements are real fields at 0 and 4.
|
||||
try std.testing.expectEqual(@as(?usize, 0), plan.elements[0].sx_field);
|
||||
try std.testing.expectEqual(@as(usize, 0), plan.elements[0].offset);
|
||||
try std.testing.expectEqual(@as(?usize, 1), plan.elements[1].sx_field);
|
||||
try std.testing.expectEqual(@as(usize, 4), plan.elements[1].offset);
|
||||
}
|
||||
|
||||
// Lock: `StructInfo` is the first NON-natural layout — Zig reorders it to
|
||||
// (fields@0, name@16, nominal_id@20, is_protocol@24) with a 7-byte alignment
|
||||
// tail. The plan must reproduce exactly that order + the sx→element remap, so the
|
||||
// LLVM type built from it is byte-identical to the Zig type. sx declaration order
|
||||
// is (name, fields, is_protocol, nominal_id) = sx indices 0,1,2,3.
|
||||
test "compiler_lib: weld plan for StructInfo reorders + pads to the Zig layout" {
|
||||
const alloc = std.testing.allocator;
|
||||
const bt = compiler_lib.findType("StructInfo").?;
|
||||
var plan = try compiler_lib.computeWeldPlan(alloc, bt.fields, bt.size);
|
||||
defer plan.deinit(alloc);
|
||||
|
||||
try std.testing.expectEqual(@as(usize, 32), plan.total_size);
|
||||
|
||||
// Elements in ascending offset order: fields, name, nominal_id, is_protocol,
|
||||
// then a trailing 7-byte pad (25 → 32).
|
||||
try std.testing.expectEqual(@as(usize, 5), plan.elements.len);
|
||||
|
||||
// elem 0: fields (sx index 1) @ 0, size 16
|
||||
try std.testing.expectEqual(@as(?usize, 1), plan.elements[0].sx_field);
|
||||
try std.testing.expectEqual(@as(usize, 0), plan.elements[0].offset);
|
||||
try std.testing.expectEqual(@as(usize, 16), plan.elements[0].size);
|
||||
// elem 1: name (sx index 0) @ 16, size 4
|
||||
try std.testing.expectEqual(@as(?usize, 0), plan.elements[1].sx_field);
|
||||
try std.testing.expectEqual(@as(usize, 16), plan.elements[1].offset);
|
||||
// elem 2: nominal_id (sx index 3) @ 20, size 4
|
||||
try std.testing.expectEqual(@as(?usize, 3), plan.elements[2].sx_field);
|
||||
try std.testing.expectEqual(@as(usize, 20), plan.elements[2].offset);
|
||||
// elem 3: is_protocol (sx index 2) @ 24, size 1
|
||||
try std.testing.expectEqual(@as(?usize, 2), plan.elements[3].sx_field);
|
||||
try std.testing.expectEqual(@as(usize, 24), plan.elements[3].offset);
|
||||
// elem 4: trailing pad @ 25, size 7
|
||||
try std.testing.expectEqual(@as(?usize, null), plan.elements[4].sx_field);
|
||||
try std.testing.expectEqual(@as(usize, 25), plan.elements[4].offset);
|
||||
try std.testing.expectEqual(@as(usize, 7), plan.elements[4].size);
|
||||
|
||||
// sx → element remap: name→1, fields→0, is_protocol→3, nominal_id→2.
|
||||
try std.testing.expectEqual(@as(usize, 1), plan.sx_to_llvm[0]);
|
||||
try std.testing.expectEqual(@as(usize, 0), plan.sx_to_llvm[1]);
|
||||
try std.testing.expectEqual(@as(usize, 3), plan.sx_to_llvm[2]);
|
||||
try std.testing.expectEqual(@as(usize, 2), plan.sx_to_llvm[3]);
|
||||
}
|
||||
|
||||
// Lock: the welded-function export list resolves the round-trip readers and
|
||||
// rejects unexported names (the boundary the interp's dispatch consults).
|
||||
test "compiler_lib: findFn resolves exported functions, rejects others" {
|
||||
try std.testing.expect(compiler_lib.findFn("intern") != null);
|
||||
try std.testing.expect(compiler_lib.findFn("text_of") != null);
|
||||
try std.testing.expectEqualStrings("intern", compiler_lib.findFn("intern").?.sx_name);
|
||||
try std.testing.expect(compiler_lib.findFn("not_exported") == null);
|
||||
try std.testing.expect(compiler_lib.findFn("") == null);
|
||||
}
|
||||
291
src/ir/compiler_lib.zig
Normal file
291
src/ir/compiler_lib.zig
Normal file
@@ -0,0 +1,291 @@
|
||||
//! The comptime `compiler` library's binding registry — the curated surface of
|
||||
//! the compiler's own types (layout-welded) and functions (host-call bridged)
|
||||
//! reachable from comptime sx via `abi(.zig) extern compiler`. See
|
||||
//! `design/comptime-compiler-api.md`.
|
||||
//!
|
||||
//! **This registry IS the safety boundary.** Only the entries registered here
|
||||
//! are bindable from user comptime code; anything not on the export list is
|
||||
//! unreachable. A welded `Name :: struct abi(.zig) extern compiler { … }` (or a
|
||||
//! welded fn) resolves its layout/dispatch against this table, not the ordinary
|
||||
//! extern-lib path.
|
||||
//!
|
||||
//! **Layout is welded, not guessed.** Because the sx compiler is itself a Zig
|
||||
//! program, the real internal type's layout is available at compiler-build time:
|
||||
//! each `BoundType` bakes `@sizeOf`/`@alignOf`/`@offsetOf` from the bound Zig
|
||||
//! type. A `types.zig` change re-bakes the offsets on the next build, so both
|
||||
//! sides move together. The sx-side `struct abi(.zig) …` declaration is then a
|
||||
//! *header* checked against these offsets (the build-time layout-equality
|
||||
//! assertion lands in the layout sub-step).
|
||||
|
||||
const std = @import("std");
|
||||
const types = @import("types.zig");
|
||||
const interp_mod = @import("interp.zig");
|
||||
const Value = interp_mod.Value;
|
||||
const Interpreter = interp_mod.Interpreter;
|
||||
const InterpError = interp_mod.InterpError;
|
||||
const StringId = types.StringId;
|
||||
|
||||
/// One field of a welded type: its sx-visible name plus the byte offset + size
|
||||
/// taken from the bound Zig type.
|
||||
pub const FieldLayout = struct {
|
||||
name: []const u8,
|
||||
offset: usize,
|
||||
size: usize,
|
||||
};
|
||||
|
||||
/// A type exported by the `compiler` library, welded to a real internal Zig
|
||||
/// type. `size`/`alignment`/`fields` are baked from that Zig type at
|
||||
/// compiler-build time (so they cannot drift from the implementation).
|
||||
pub const BoundType = struct {
|
||||
/// The sx-side name a welded `struct abi(.zig) extern compiler` uses.
|
||||
sx_name: []const u8,
|
||||
size: usize,
|
||||
alignment: usize,
|
||||
fields: []const FieldLayout,
|
||||
};
|
||||
|
||||
/// The real internal Zig type each welded export binds to. Kept as named
|
||||
/// aliases so the binding sites read as a curated list.
|
||||
const FieldZig = types.TypeInfo.StructInfo.Field; // { name: StringId, ty: TypeId } — two u32s
|
||||
const StructInfoZig = types.TypeInfo.StructInfo; // { name, fields: []Field, is_protocol, nominal_id } — Zig-reordered
|
||||
|
||||
/// Bake a `BoundType` from a real Zig struct type `T`. Field offsets/sizes come
|
||||
/// from `@offsetOf`/`@sizeOf` on `T`; `sx_field_names` supplies the sx-visible
|
||||
/// names positionally (must match `T`'s field order and count — a mismatch is a
|
||||
/// compile error, never a silent truncation).
|
||||
fn weldStruct(
|
||||
comptime sx_name: []const u8,
|
||||
comptime T: type,
|
||||
comptime sx_field_names: []const []const u8,
|
||||
) BoundType {
|
||||
const zig_fields = @typeInfo(T).@"struct".fields;
|
||||
if (zig_fields.len != sx_field_names.len)
|
||||
@compileError("compiler-lib weld '" ++ sx_name ++ "': sx field count != Zig field count");
|
||||
comptime var layouts: [zig_fields.len]FieldLayout = undefined;
|
||||
inline for (zig_fields, 0..) |zf, i| {
|
||||
layouts[i] = .{
|
||||
.name = sx_field_names[i],
|
||||
.offset = @offsetOf(T, zf.name),
|
||||
.size = @sizeOf(zf.type),
|
||||
};
|
||||
}
|
||||
const frozen = layouts;
|
||||
return .{
|
||||
.sx_name = sx_name,
|
||||
.size = @sizeOf(T),
|
||||
.alignment = @alignOf(T),
|
||||
.fields = &frozen,
|
||||
};
|
||||
}
|
||||
|
||||
/// The welded-type export list. `Field` (two u32s, natural layout) proved the
|
||||
/// weld in Phase 1; `StructInfo` (Phase 2) is the first NON-natural layout —
|
||||
/// Zig reorders its fields (`fields`@0, `name`@16, `nominal_id`@20,
|
||||
/// `is_protocol`@24), so it exercises the offset-override engine. `EnumInfo` /
|
||||
/// `TaggedUnionInfo` / `TupleInfo` join later.
|
||||
pub const bound_types = [_]BoundType{
|
||||
weldStruct("Field", FieldZig, &.{ "name", "ty" }),
|
||||
weldStruct("StructInfo", StructInfoZig, &.{ "name", "fields", "is_protocol", "nominal_id" }),
|
||||
};
|
||||
|
||||
/// Look up a welded type by its sx name. Returns null when the name is not on
|
||||
/// the `compiler` library's export list (the lookup the welded-decl resolution
|
||||
/// path consults instead of the ordinary extern-lib path).
|
||||
pub fn findType(sx_name: []const u8) ?*const BoundType {
|
||||
for (&bound_types) |*bt| {
|
||||
if (std.mem.eql(u8, bt.sx_name, sx_name)) return bt;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The name of the only welded library. A `struct abi(.zig) extern <lib>` with a
|
||||
/// different `<lib>` is rejected — `compiler` is the sole comptime weld source.
|
||||
pub const lib_name = "compiler";
|
||||
|
||||
/// One field of an sx welded-struct declaration, as the lowering observed it:
|
||||
/// the field's sx name plus the size the sx type system computed for its type.
|
||||
pub const SxField = struct {
|
||||
name: []const u8,
|
||||
size: usize,
|
||||
};
|
||||
|
||||
/// The first way an sx welded-struct declaration fails to faithfully mirror the
|
||||
/// bound Zig type. The sx declaration is a *header* checked against the real
|
||||
/// implementation, so any drift is a build error rather than a silent
|
||||
/// reinterpretation. The caller renders the chosen variant into a diagnostic.
|
||||
pub const LayoutMismatch = union(enum) {
|
||||
/// The sx declaration has a different field count than the welded type.
|
||||
field_count: struct { expected: usize, got: usize },
|
||||
/// Field `index` carries the wrong sx name (a weld is positional + by-name).
|
||||
field_name: struct { index: usize, expected: []const u8, got: []const u8 },
|
||||
/// Field `index` (`name`) is a different size than the welded type's field.
|
||||
field_size: struct { index: usize, name: []const u8, expected: usize, got: usize },
|
||||
/// The total struct size differs (padding / alignment drift).
|
||||
total_size: struct { expected: usize, got: usize },
|
||||
};
|
||||
|
||||
/// Check an sx welded-struct declaration against the bound Zig type. Returns the
|
||||
/// FIRST mismatch, or null if the sx declaration is a faithful header. Fields are
|
||||
/// checked positionally + by name + by size, and the total size is compared — for
|
||||
/// a natural (C-like) layout this catches a missing/extra field (count), a rename
|
||||
/// or reorder (name), a retype (size), and padding drift (total). Explicit
|
||||
/// per-field OFFSET overrides (for non-natural Zig layouts — slices, reordered or
|
||||
/// `union(enum)` fields) arrive with `StructInfo` in Phase 2; `Field`'s two-u32
|
||||
/// natural layout needs none.
|
||||
pub fn validateStructLayout(
|
||||
bt: *const BoundType,
|
||||
sx_fields: []const SxField,
|
||||
sx_total_size: usize,
|
||||
) ?LayoutMismatch {
|
||||
if (sx_fields.len != bt.fields.len)
|
||||
return .{ .field_count = .{ .expected = bt.fields.len, .got = sx_fields.len } };
|
||||
for (sx_fields, bt.fields, 0..) |sf, bf, i| {
|
||||
if (!std.mem.eql(u8, sf.name, bf.name))
|
||||
return .{ .field_name = .{ .index = i, .expected = bf.name, .got = sf.name } };
|
||||
if (sf.size != bf.size)
|
||||
return .{ .field_size = .{ .index = i, .name = bf.name, .expected = bf.size, .got = sf.size } };
|
||||
}
|
||||
if (sx_total_size != bt.size)
|
||||
return .{ .total_size = .{ .expected = bt.size, .got = sx_total_size } };
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── Weld plan (byte-layout override) ────────────────────────────────────────
|
||||
//
|
||||
// A welded struct must be laid out byte-identically to the bound Zig type, whose
|
||||
// fields Zig may REORDER (and pad). The sx struct's natural layout generally
|
||||
// won't match — so the compiler imposes the Zig layout: it builds the struct's
|
||||
// LLVM type as the fields in ascending-OFFSET order, with explicit padding
|
||||
// elements filling the gaps, and remaps each sx field index to its LLVM element
|
||||
// index. `computeWeldPlan` is that pure layout math; the LLVM type builder + the
|
||||
// struct-GEP / field-access sites consume the plan (later sub-steps), and the
|
||||
// interp serializes comptime struct Values through the same offsets.
|
||||
|
||||
/// One element of a welded struct's LLVM layout: either a real field (carrying
|
||||
/// its sx field index) or a padding gap. Always in ascending `offset` order.
|
||||
pub const WeldElement = struct {
|
||||
/// The sx field index this element holds, or null for a padding gap.
|
||||
sx_field: ?usize,
|
||||
/// Byte offset of this element within the struct (the bound Zig offset).
|
||||
offset: usize,
|
||||
/// Byte width of this element (the field's size, or the gap width).
|
||||
size: usize,
|
||||
};
|
||||
|
||||
/// The byte-layout plan for a welded struct: its LLVM elements in offset order
|
||||
/// (fields + padding) and the sx-field → LLVM-element-index remap. Owns its
|
||||
/// slices — `deinit` with the same allocator passed to `computeWeldPlan`.
|
||||
pub const WeldPlan = struct {
|
||||
elements: []const WeldElement,
|
||||
/// `sx_to_llvm[i]` is the index into `elements` of sx field `i`.
|
||||
sx_to_llvm: []const usize,
|
||||
total_size: usize,
|
||||
|
||||
pub fn deinit(self: *WeldPlan, alloc: std.mem.Allocator) void {
|
||||
alloc.free(self.elements);
|
||||
alloc.free(self.sx_to_llvm);
|
||||
}
|
||||
};
|
||||
|
||||
/// Compute the byte-layout plan for a struct whose fields carry their bound Zig
|
||||
/// offsets (`fields[i].offset`/`.size`, e.g. from a `BoundType`). `total_size` is
|
||||
/// the bound Zig `@sizeOf`. The result lists LLVM elements in ascending-offset
|
||||
/// order — real fields interleaved with padding gaps — plus the sx-field →
|
||||
/// element-index remap that struct-GEP uses. Pure; allocates the result slices.
|
||||
pub fn computeWeldPlan(
|
||||
alloc: std.mem.Allocator,
|
||||
fields: []const FieldLayout,
|
||||
total_size: usize,
|
||||
) !WeldPlan {
|
||||
// Order the sx field indices by ascending byte offset (stable).
|
||||
const order = try alloc.alloc(usize, fields.len);
|
||||
defer alloc.free(order);
|
||||
for (order, 0..) |*o, i| o.* = i;
|
||||
std.sort.insertion(usize, order, fields, struct {
|
||||
fn lessThan(fs: []const FieldLayout, a: usize, b: usize) bool {
|
||||
return fs[a].offset < fs[b].offset;
|
||||
}
|
||||
}.lessThan);
|
||||
|
||||
var elements = std.ArrayList(WeldElement).empty;
|
||||
errdefer elements.deinit(alloc);
|
||||
const sx_to_llvm = try alloc.alloc(usize, fields.len);
|
||||
errdefer alloc.free(sx_to_llvm);
|
||||
|
||||
var cursor: usize = 0;
|
||||
for (order) |sx_i| {
|
||||
const f = fields[sx_i];
|
||||
// Fill any gap before this field with a padding element.
|
||||
if (f.offset > cursor) {
|
||||
try elements.append(alloc, .{ .sx_field = null, .offset = cursor, .size = f.offset - cursor });
|
||||
}
|
||||
sx_to_llvm[sx_i] = elements.items.len;
|
||||
try elements.append(alloc, .{ .sx_field = sx_i, .offset = f.offset, .size = f.size });
|
||||
cursor = f.offset + f.size;
|
||||
}
|
||||
// Trailing padding up to the bound total size (alignment tail).
|
||||
if (total_size > cursor) {
|
||||
try elements.append(alloc, .{ .sx_field = null, .offset = cursor, .size = total_size - cursor });
|
||||
}
|
||||
|
||||
return .{
|
||||
.elements = try elements.toOwnedSlice(alloc),
|
||||
.sx_to_llvm = sx_to_llvm,
|
||||
.total_size = total_size,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Functions (comptime-only, host-call bridged) ────────────────────────────
|
||||
|
||||
/// A welded `compiler` function: dispatched under the comptime interpreter to its
|
||||
/// Zig handler (never dlsym'd). The handler receives the interpreter (for the
|
||||
/// string pool / type table) and the already-evaluated argument `Value`s, and
|
||||
/// returns the result `Value`.
|
||||
pub const FnHandler = *const fn (interp: *Interpreter, args: []const Value) InterpError!Value;
|
||||
|
||||
pub const BoundFn = struct {
|
||||
sx_name: []const u8,
|
||||
handler: FnHandler,
|
||||
};
|
||||
|
||||
/// The welded-function export list. Start small (Phase 1): the `StringId`
|
||||
/// round-trip readers. `find_type` / the guarded `register_*` mutators join in
|
||||
/// later phases.
|
||||
pub const bound_fns = [_]BoundFn{
|
||||
.{ .sx_name = "intern", .handler = handleIntern },
|
||||
.{ .sx_name = "text_of", .handler = handleTextOf },
|
||||
};
|
||||
|
||||
/// Look up a welded function by its sx name. Returns null when the name is not on
|
||||
/// the `compiler` library's function-export list.
|
||||
pub fn findFn(sx_name: []const u8) ?*const BoundFn {
|
||||
for (&bound_fns) |*bf| {
|
||||
if (std.mem.eql(u8, bf.sx_name, sx_name)) return bf;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The comptime type table to intern into: the host's mutable mint target when
|
||||
/// set (the metatype-construction path), else the module's table reached through
|
||||
/// a const-cast — the same access the interp's mint path uses (interp.zig). The
|
||||
/// underlying table is genuinely mutable; the interp merely holds it `const`.
|
||||
fn mintTable(interp: *Interpreter) *types.TypeTable {
|
||||
return interp.mint orelse @constCast(&interp.module.types);
|
||||
}
|
||||
|
||||
/// `intern(s: string) -> StringId` — intern `s` into the compiler's string pool
|
||||
/// and return its handle. The inverse of `text_of`.
|
||||
fn handleIntern(interp: *Interpreter, args: []const Value) InterpError!Value {
|
||||
if (args.len != 1 or args[0] != .string) return error.TypeError;
|
||||
const id = mintTable(interp).internString(args[0].string);
|
||||
return Value{ .int = @intFromEnum(id) };
|
||||
}
|
||||
|
||||
/// `text_of(id: StringId) -> string` — resolve a string handle back to its text.
|
||||
/// The inverse of `intern`.
|
||||
fn handleTextOf(interp: *Interpreter, args: []const Value) InterpError!Value {
|
||||
if (args.len != 1 or args[0] != .int) return error.TypeError;
|
||||
if (args[0].int < 0 or args[0].int > std.math.maxInt(u32)) return error.TypeError;
|
||||
const id: StringId = @enumFromInt(@as(u32, @intCast(args[0].int)));
|
||||
return Value{ .string = interp.module.types.getString(id) };
|
||||
}
|
||||
@@ -1273,7 +1273,7 @@ pub const LLVMEmitter = struct {
|
||||
else if (needs_c_abi) self.abiCoerceParamTypeEx(func.ret, raw_ret_ty, func.is_extern)
|
||||
else raw_ret_ty;
|
||||
|
||||
// Build parameter types — apply C ABI coercion for extern/callconv(.c) functions.
|
||||
// Build parameter types — apply C ABI coercion for extern/abi(.c) functions.
|
||||
// When uses_sret, prepend the sret pointer at index 0.
|
||||
const sret_offset: usize = if (uses_sret) 1 else 0;
|
||||
const param_count: c_uint = @intCast(func.params.len + sret_offset);
|
||||
|
||||
@@ -575,8 +575,14 @@ pub const Function = struct {
|
||||
/// parameter that every default-conv sx function receives. Callers
|
||||
/// read this flag to decide whether to prepend their current
|
||||
/// `__sx_ctx` value to the args of a call. Extern decls and
|
||||
/// `callconv(.c)` functions have it false.
|
||||
/// `abi(.c)` functions have it false.
|
||||
has_implicit_ctx: bool = false,
|
||||
/// True for a `fn abi(.zig) extern compiler` welded to the comptime
|
||||
/// `compiler` library. Such a function has no real symbol — the comptime
|
||||
/// interpreter dispatches it to its registered Zig handler
|
||||
/// (`compiler_lib.findFn`) instead of dlsym. Comptime-only; a runtime call
|
||||
/// has no backing symbol. See design/comptime-compiler-api.md.
|
||||
compiler_welded: bool = false,
|
||||
|
||||
pub const Param = struct {
|
||||
name: StringId,
|
||||
|
||||
@@ -162,6 +162,7 @@ pub const InterpError = error{
|
||||
|
||||
const compiler_hooks = @import("compiler_hooks.zig");
|
||||
pub const BuildConfig = compiler_hooks.BuildConfig;
|
||||
const compiler_lib = @import("compiler_lib.zig");
|
||||
const host_ffi = @import("host_ffi.zig");
|
||||
|
||||
// ── Interpreter ─────────────────────────────────────────────────────────
|
||||
@@ -579,6 +580,15 @@ pub const Interpreter = struct {
|
||||
defer self.call_depth -= 1;
|
||||
|
||||
const func = self.module.getFunction(func_id);
|
||||
// Welded `compiler`-library function: dispatch to its registered Zig
|
||||
// handler (comptime-only), never dlsym. The binding registry IS the
|
||||
// safety boundary — a name not on the export list is a clean bail.
|
||||
if (func.compiler_welded) {
|
||||
const fname = self.module.types.getString(func.name);
|
||||
const bf = compiler_lib.findFn(fname) orelse
|
||||
return bailDetail("comptime compiler call: function not exported by the compiler library");
|
||||
return bf.handler(self, args);
|
||||
}
|
||||
if (func.is_extern or func.blocks.items.len == 0) {
|
||||
// Dispatch to host libc via dlsym. Lets `#run` (and the
|
||||
// post-link bundler) call ordinary extern symbols like
|
||||
|
||||
@@ -60,6 +60,7 @@ pub const ObjcLowering = ffi_objc.ObjcLowering;
|
||||
pub const ErrorFacts = error_analysis.ErrorFacts;
|
||||
|
||||
pub const compiler_hooks = @import("compiler_hooks.zig");
|
||||
pub const compiler_lib = @import("compiler_lib.zig");
|
||||
pub const emit_llvm = @import("emit_llvm.zig");
|
||||
pub const LLVMEmitter = emit_llvm.LLVMEmitter;
|
||||
|
||||
@@ -89,6 +90,7 @@ pub const type_bridge_tests = @import("type_bridge.test.zig");
|
||||
pub const emit_llvm_tests = @import("emit_llvm.test.zig");
|
||||
pub const jni_descriptor_tests = @import("jni_descriptor.test.zig");
|
||||
pub const jni_java_emit_tests = @import("jni_java_emit.test.zig");
|
||||
pub const compiler_lib_tests = @import("compiler_lib.test.zig");
|
||||
|
||||
test {
|
||||
@import("std").testing.refAllDecls(@This());
|
||||
|
||||
@@ -78,7 +78,7 @@ pub fn lowerLambda(self: *Lowering, lam: *const ast.Lambda) Ref {
|
||||
// Without implicit_ctx, env is slot 0 and user params follow.
|
||||
var params = std.ArrayList(Function.Param).empty;
|
||||
const env_ptr_ty = self.module.types.ptrTo(.void);
|
||||
const lambda_wants_ctx = self.implicit_ctx_enabled and lam.call_conv != .c;
|
||||
const lambda_wants_ctx = self.implicit_ctx_enabled and lam.abi != .c;
|
||||
if (lambda_wants_ctx) {
|
||||
params.append(self.alloc, .{
|
||||
.name = self.module.types.internString("__sx_ctx"),
|
||||
@@ -168,7 +168,7 @@ pub fn lowerLambda(self: *Lowering, lam: *const ast.Lambda) Ref {
|
||||
};
|
||||
const name_id = self.module.types.internString(name);
|
||||
const func_id = self.builder.beginFunction(name_id, params.items, ret_ty);
|
||||
if (lam.call_conv == .c) {
|
||||
if (lam.abi == .c) {
|
||||
self.module.getFunctionMut(func_id).call_conv = .c;
|
||||
}
|
||||
self.builder.currentFunc().has_implicit_ctx = lambda_wants_ctx;
|
||||
|
||||
@@ -10,6 +10,7 @@ const unescape = @import("../../unescape.zig");
|
||||
const errors = @import("../../errors.zig");
|
||||
const program_index_mod = @import("../program_index.zig");
|
||||
const resolver_mod = @import("../resolver.zig");
|
||||
const compiler_lib = @import("../compiler_lib.zig");
|
||||
const ProgramIndex = program_index_mod.ProgramIndex;
|
||||
const GlobalInfo = program_index_mod.GlobalInfo;
|
||||
const ModuleConstInfo = program_index_mod.ModuleConstInfo;
|
||||
@@ -497,7 +498,7 @@ pub fn detectContextDecl(decls: []const *const Node) bool {
|
||||
/// `__sx_<name>_impl` with the ctx param) lands in Step 4 proper.
|
||||
pub fn funcWantsImplicitCtx(self: *const Lowering, fd: *const ast.FnDecl) bool {
|
||||
if (!self.implicit_ctx_enabled) return false;
|
||||
if (fd.call_conv == .c) return false;
|
||||
if (fd.abi == .c) return false;
|
||||
// `extern` imports and `export` defines are external C symbols —
|
||||
// C ABI, no sx context (Phase 2, gap iv).
|
||||
if (fd.extern_export != .none) return false;
|
||||
@@ -2256,11 +2257,11 @@ pub fn declareFunction(self: *Lowering, fd: *const ast.FnDecl, name: []const u8)
|
||||
}
|
||||
|
||||
// `extern` declarations are external C symbols by definition — promote
|
||||
// them to callconv(.c) when the user didn't write it explicitly. This keeps
|
||||
// them to abi(.c) when the user didn't write it explicitly. This keeps
|
||||
// fn-ptr coercion type-safe: anything typed by name as `(args) -> ret` of an
|
||||
// `extern` decl can be assigned to / passed as a `callconv(.c)` fn-pointer
|
||||
// `extern` decl can be assigned to / passed as a `abi(.c)` fn-pointer
|
||||
// without a call-convention mismatch.
|
||||
const cc: Function.CallingConvention = if (fd.call_conv == .c or is_extern_decl or fd.extern_export == .export_) .c else .default;
|
||||
const cc: Function.CallingConvention = if (fd.abi == .c or is_extern_decl or fd.extern_export == .export_) .c else .default;
|
||||
|
||||
// Symbol-name override: `extern … "csym"` / `export … "csym"` (fd.extern_name).
|
||||
// Declare under the C name and map the sx name → C name so call sites resolve
|
||||
@@ -2296,9 +2297,29 @@ pub fn declareFunction(self: *Lowering, fd: *const ast.FnDecl, name: []const u8)
|
||||
func.source_file = self.current_source_file;
|
||||
func.is_variadic = is_variadic;
|
||||
func.has_implicit_ctx = wants_ctx;
|
||||
if (weldedCompilerFn(self, fd, name)) func.compiler_welded = true;
|
||||
self.fn_decl_fids.put(fd, fid) catch {};
|
||||
}
|
||||
|
||||
/// A `fn abi(.zig) extern <lib>` binds the comptime `compiler` library. Validate
|
||||
/// it (the bound lib must be `compiler`; the name must be on the function-export
|
||||
/// list) and return whether it is a welded compiler function — the interpreter
|
||||
/// dispatches such a call to its registered Zig handler instead of dlsym. Any
|
||||
/// failure is a build-gating `.err` (never a silent fall-through to dlsym).
|
||||
fn weldedCompilerFn(self: *Lowering, fd: *const ast.FnDecl, name: []const u8) bool {
|
||||
if (fd.abi != .zig) return false;
|
||||
const diags = self.diagnostics;
|
||||
if (fd.extern_lib == null or !std.mem.eql(u8, fd.extern_lib.?, compiler_lib.lib_name)) {
|
||||
if (diags) |d| d.addFmt(.err, fd.name_span, "abi(.zig) function '{s}' must bind the compiler library — write `extern {s}`", .{ name, compiler_lib.lib_name });
|
||||
return false;
|
||||
}
|
||||
if (compiler_lib.findFn(name) == null) {
|
||||
if (diags) |d| d.addFmt(.err, fd.name_span, "'{s}' is not a function exported by the '{s}' library", .{ name, compiler_lib.lib_name });
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Register a namespaced import's OWN functions under their module-qualified
|
||||
/// name (`ns.fn`), giving each a UNIQUE FuncId in the function table. Two
|
||||
/// modules each exporting a top-level `parse` otherwise collide in the
|
||||
@@ -2553,7 +2574,7 @@ pub fn lowerFunctionBodyInto(self: *Lowering, fd: *const ast.FnDecl, fid: FuncId
|
||||
func.is_extern = false; // promote from extern stub to real function
|
||||
// `export` defines force external linkage + C ABI (Phase 2, gaps i+ii).
|
||||
func.linkage = if (isExportedEntryName(name) or fd.extern_export == .export_) .external else .internal;
|
||||
if (fd.call_conv == .c or fd.extern_export == .export_) func.call_conv = .c;
|
||||
if (fd.abi == .c or fd.extern_export == .export_) func.call_conv = .c;
|
||||
// Set inst_counter to param count (params occupy refs 0..N-1). IR params
|
||||
// = AST params + 1 if the function carries `__sx_ctx` at slot 0.
|
||||
const ctx_slots: usize = if (func.has_implicit_ctx) 1 else 0;
|
||||
@@ -2589,7 +2610,7 @@ pub fn lowerFunctionBodyInto(self: *Lowering, fd: *const ast.FnDecl, fid: FuncId
|
||||
scope.put(p.name, .{ .ref = slot, .ty = pty, .is_alloca = true });
|
||||
}
|
||||
|
||||
// Inbound entry points + callconv(.c) sx functions: bind current_ctx_ref
|
||||
// Inbound entry points + abi(.c) sx functions: bind current_ctx_ref
|
||||
// to the static default before any user code runs.
|
||||
if (!wants_ctx and self.implicit_ctx_enabled) {
|
||||
if (self.program_index.global_names.get("__sx_default_context")) |dctx_gi| {
|
||||
@@ -2695,7 +2716,7 @@ pub fn lowerFunction(self: *Lowering, fd: *const ast.FnDecl, name: []const u8, i
|
||||
}
|
||||
|
||||
// Set calling convention. `export` defines promote to C ABI (gap ii).
|
||||
if (fd.call_conv == .c or fd.extern_export == .export_) {
|
||||
if (fd.abi == .c or fd.extern_export == .export_) {
|
||||
self.builder.currentFunc().call_conv = .c;
|
||||
}
|
||||
|
||||
@@ -2729,7 +2750,7 @@ pub fn lowerFunction(self: *Lowering, fd: *const ast.FnDecl, name: []const u8, i
|
||||
scope.put(p.name, .{ .ref = slot, .ty = pty, .is_alloca = true });
|
||||
}
|
||||
|
||||
// Inbound entry points + callconv(.c) sx functions: bind
|
||||
// Inbound entry points + abi(.c) sx functions: bind
|
||||
// current_ctx_ref to &__sx_default_context. See companion comment
|
||||
// in `lowerFunction` for the same case.
|
||||
if (!wants_ctx_lf and self.implicit_ctx_enabled) {
|
||||
|
||||
@@ -1894,7 +1894,7 @@ pub fn lowerExpr(self: *Lowering, node: *const Node) Ref {
|
||||
// Coercing a bare fn name to a fn-pointer
|
||||
// type — the call_conv must match. A
|
||||
// default-conv sx fn assigned to a
|
||||
// callconv(.c) slot (e.g. passed to
|
||||
// abi(.c) slot (e.g. passed to
|
||||
// pthread_create) would otherwise crash at
|
||||
// runtime when the C caller doesn't supply
|
||||
// the implicit __sx_ctx arg.
|
||||
@@ -1902,8 +1902,8 @@ pub fn lowerExpr(self: *Lowering, node: *const Node) Ref {
|
||||
const func_cc = self.module.functions.items[@intFromEnum(fid)].call_conv;
|
||||
if (func_cc != tt_info.function.call_conv) {
|
||||
if (self.diagnostics) |d| {
|
||||
const want_cc = if (tt_info.function.call_conv == .c) "callconv(.c)" else "default sx convention";
|
||||
const have_cc = if (func_cc == .c) "callconv(.c)" else "default sx convention";
|
||||
const want_cc = if (tt_info.function.call_conv == .c) "abi(.c)" else "default sx convention";
|
||||
const have_cc = if (func_cc == .c) "abi(.c)" else "default sx convention";
|
||||
d.addFmt(.err, node.span, "call-convention mismatch: '{s}' is declared with {s} but the target type expects {s}", .{ eff_fn_name, have_cc, want_cc });
|
||||
}
|
||||
break :blk self.emitPlaceholder(eff_fn_name);
|
||||
|
||||
@@ -1133,7 +1133,7 @@ pub fn synthesizeJniMainStub(self: *Lowering, fcd: *const ast.RuntimeClassDecl,
|
||||
// JNI native methods are C-callable entry points — install the
|
||||
// static default Context so `context.X` reads in the method body
|
||||
// resolve through `current_ctx_ref`. Mirror the same binding
|
||||
// `lowerFunction` does for callconv(.c) / isExportedEntryName.
|
||||
// `lowerFunction` does for abi(.c) / isExportedEntryName.
|
||||
const saved_ctx_ref_jni = self.current_ctx_ref;
|
||||
defer self.current_ctx_ref = saved_ctx_ref_jni;
|
||||
if (self.implicit_ctx_enabled) {
|
||||
|
||||
@@ -6,6 +6,7 @@ const mod_mod = @import("../module.zig");
|
||||
const type_bridge = @import("../type_bridge.zig");
|
||||
const program_index_mod = @import("../program_index.zig");
|
||||
const resolver_mod = @import("../resolver.zig");
|
||||
const compiler_lib = @import("../compiler_lib.zig");
|
||||
const StructTemplate = program_index_mod.StructTemplate;
|
||||
const TemplateParam = program_index_mod.TemplateParam;
|
||||
|
||||
@@ -673,7 +674,13 @@ pub fn registerStructDecl(self: *Lowering, sd: *const ast.StructDecl, source_fil
|
||||
// any forward-reference stub. Same-name structs in DIFFERENT sources get
|
||||
// distinct TypeIds instead of last-wins clobbering the first.
|
||||
const info: types.TypeInfo = .{ .@"struct" = .{ .name = name_id, .fields = fields.items } };
|
||||
_ = self.internNamedTypeDecl(decl_key, name_id, info, nominal_id);
|
||||
const struct_tid = self.internNamedTypeDecl(decl_key, name_id, info, nominal_id);
|
||||
|
||||
// Welded `struct abi(.zig) extern compiler { … }`: the sx declaration is a
|
||||
// header checked against the compiler's real Zig type — validate the layout
|
||||
// matches the binding registry (a mismatch is a build error). See
|
||||
// design/comptime-compiler-api.md.
|
||||
if (sd.abi == .zig) validateWeldedStruct(self, sd, struct_tid, fields.items);
|
||||
|
||||
// Store field defaults for struct literal lowering
|
||||
if (sd.field_defaults.len > 0) {
|
||||
@@ -709,6 +716,51 @@ pub fn registerStructDecl(self: *Lowering, sd: *const ast.StructDecl, source_fil
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate a welded `struct abi(.zig) extern <lib> { … }` against the `compiler`
|
||||
/// library's binding registry: the bound library must be `compiler`, the name
|
||||
/// must be on the export list, and the sx-declared layout must match the real Zig
|
||||
/// type's (the sx side is a *header* checked against the implementation). Any
|
||||
/// failure is a build-gating `.err` diagnostic — never a silent reinterpretation.
|
||||
fn validateWeldedStruct(self: *Lowering, sd: *const ast.StructDecl, tid: TypeId, fields: []const types.TypeInfo.StructInfo.Field) void {
|
||||
const diags = self.diagnostics orelse return;
|
||||
const table = &self.module.types;
|
||||
|
||||
// A span that points into the struct (its first field, else zero) — the decl
|
||||
// has no name span of its own.
|
||||
const span: ast.Span = if (sd.field_types.len > 0) sd.field_types[0].span else .{ .start = 0, .end = 0 };
|
||||
|
||||
// The bound library must be the sole welded source.
|
||||
if (sd.extern_lib == null or !std.mem.eql(u8, sd.extern_lib.?, compiler_lib.lib_name)) {
|
||||
diags.addFmt(.err, span, "abi(.zig) struct '{s}' must bind the compiler library — write `extern {s}`", .{ sd.name, compiler_lib.lib_name });
|
||||
return;
|
||||
}
|
||||
|
||||
// The name must be on the curated export list (the safety boundary).
|
||||
const bt = compiler_lib.findType(sd.name) orelse {
|
||||
diags.addFmt(.err, span, "'{s}' is not a type exported by the '{s}' library", .{ sd.name, compiler_lib.lib_name });
|
||||
return;
|
||||
};
|
||||
|
||||
// Build the observed sx layout (field name + computed size) and total size.
|
||||
var sx_fields = std.ArrayList(compiler_lib.SxField).empty;
|
||||
defer sx_fields.deinit(self.alloc);
|
||||
for (fields) |f| {
|
||||
sx_fields.append(self.alloc, .{
|
||||
.name = table.getString(f.name),
|
||||
.size = table.typeSizeBytes(f.ty),
|
||||
}) catch return;
|
||||
}
|
||||
const total = table.typeSizeBytes(tid);
|
||||
|
||||
const mismatch = compiler_lib.validateStructLayout(bt, sx_fields.items, total) orelse return;
|
||||
switch (mismatch) {
|
||||
.field_count => |m| diags.addFmt(.err, span, "welded type '{s}' has {d} field(s) in the compiler library but the declaration has {d}", .{ sd.name, m.expected, m.got }),
|
||||
.field_name => |m| diags.addFmt(.err, span, "welded type '{s}' field {d} is named '{s}' in the compiler library, not '{s}'", .{ sd.name, m.index, m.expected, m.got }),
|
||||
.field_size => |m| diags.addFmt(.err, span, "welded type '{s}' field '{s}' is {d} byte(s) in the compiler library but {d} as declared", .{ sd.name, m.name, m.expected, m.got }),
|
||||
.total_size => |m| diags.addFmt(.err, span, "welded type '{s}' is {d} byte(s) in the compiler library but {d} as declared (padding/alignment mismatch)", .{ sd.name, m.expected, m.got }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Register a top-level ENUM decl under a per-decl nominal identity (E6a) —
|
||||
/// the enum twin of `registerStructDecl`. A GENUINE same-name shadow already
|
||||
/// reserved its DISTINCT slot up-front in `scanDecls` (the first at id 0, the
|
||||
|
||||
@@ -255,7 +255,7 @@ pub fn lowerObjcPropertySetter(self: *Lowering, obj_expr: *const ast.Node, field
|
||||
} }, .void);
|
||||
}
|
||||
|
||||
/// Get a FuncId for an external C-callconv function. If a function
|
||||
/// Get a FuncId for an external C-ABI function. If a function
|
||||
/// with this exported name already exists in the module (e.g.
|
||||
/// declared by stdlib `extern` decl), return it; otherwise
|
||||
/// declare it fresh with the given signature.
|
||||
@@ -290,7 +290,7 @@ pub fn ensureCRuntimeDecl(self: *Lowering, name: []const u8, param_tys: []const
|
||||
/// 2. Calls `object_getIvar(obj, ivar)` to get the `*<Cls>State`
|
||||
/// state pointer.
|
||||
/// 3. Calls the sx body `@<Cls>.<method>(__sx_default_context,
|
||||
/// state, ...user_args)` (default sx-callconv).
|
||||
/// state, ...user_args)` (default sx convention).
|
||||
/// 4. Returns the result (or `ret void`).
|
||||
///
|
||||
/// IMP name: `__<ClassName>_<methodName>_imp`. emit_llvm's
|
||||
|
||||
@@ -91,7 +91,7 @@ pub const Module = struct {
|
||||
pub const ObjcDefinedMethodEntry = struct {
|
||||
sel: []const u8, // mangled Obj-C selector (`add:and:`)
|
||||
encoding: []const u8, // Apple-runtime type encoding (`v@:ii`)
|
||||
imp_name: []const u8, // C-callconv trampoline symbol (`__Cls_method_imp`)
|
||||
imp_name: []const u8, // C-ABI trampoline symbol (`__Cls_method_imp`)
|
||||
is_class: bool = false, // true ⇒ register on the metaclass (M2.1 class methods)
|
||||
};
|
||||
|
||||
|
||||
@@ -224,9 +224,15 @@ pub const TypeResolver = struct {
|
||||
defer param_ids.deinit(table.alloc);
|
||||
for (ft.param_types) |pt| param_ids.append(table.alloc, inner.resolveInner(pt)) catch return .unresolved;
|
||||
const ret_ty = if (ft.return_type) |rt| inner.resolveInner(rt) else TypeId.void;
|
||||
const cc: types.TypeInfo.CallConv = switch (ft.call_conv) {
|
||||
const cc: types.TypeInfo.CallConv = switch (ft.abi) {
|
||||
.default => .default,
|
||||
.c => .c,
|
||||
// `.zig` (compiler-lib weld) and `.pure` (naked asm) are
|
||||
// decl-level ABIs with no function-pointer-type calling
|
||||
// convention of their own; the IR function-type CC models only
|
||||
// sx-default vs C. Neither occurs in a function-TYPE position in
|
||||
// current usage — treated as sx-default here.
|
||||
.zig, .pure => .default,
|
||||
};
|
||||
break :blk table.functionTypeCC(param_ids.items, ret_ty, cc);
|
||||
},
|
||||
|
||||
@@ -537,9 +537,9 @@ test "lex keywords" {
|
||||
}
|
||||
|
||||
test "lex linkage keywords" {
|
||||
// extern / export are keywords (FFI-linkage stream), lexed beside callconv.
|
||||
var lex = Lexer.init("callconv extern export");
|
||||
const expected = [_]Tag{ .kw_callconv, .kw_extern, .kw_export };
|
||||
// extern / export are keywords (FFI-linkage stream), lexed beside abi.
|
||||
var lex = Lexer.init("abi extern export");
|
||||
const expected = [_]Tag{ .kw_abi, .kw_extern, .kw_export };
|
||||
for (expected) |exp| {
|
||||
try std.testing.expectEqual(exp, lex.next().tag);
|
||||
}
|
||||
|
||||
@@ -1682,7 +1682,7 @@ pub const Server = struct {
|
||||
.kw_protocol,
|
||||
.kw_impl,
|
||||
.kw_inline,
|
||||
.kw_callconv,
|
||||
.kw_abi,
|
||||
.kw_extern,
|
||||
.kw_export,
|
||||
.kw_asm,
|
||||
|
||||
@@ -909,6 +909,11 @@ fn extractLibraries(allocator: std.mem.Allocator, root: *const sx.ast.Node) ![]c
|
||||
for (decls) |d| {
|
||||
switch (d.data) {
|
||||
.library_decl => |ld| {
|
||||
// The `compiler` library is the comptime-only internal
|
||||
// surface (welded types / host-call functions), not a
|
||||
// linkable dylib — never dlopen it. See
|
||||
// design/comptime-compiler-api.md.
|
||||
if (std.mem.eql(u8, ld.lib_name, sx.ir.compiler_lib.lib_name)) continue;
|
||||
if (s.contains(ld.lib_name)) continue;
|
||||
try s.put(ld.lib_name, {});
|
||||
try l.append(a, ld.lib_name);
|
||||
|
||||
@@ -78,3 +78,148 @@ test "parser: comptime type-metaprogramming surface parses" {
|
||||
try std.testing.expect(d.data.fn_decl.return_type != null);
|
||||
}
|
||||
}
|
||||
|
||||
// Lock: the `compiler`-library binding surface PARSES — `name :: #library "x";`
|
||||
// (already supported) plus the new postfix `abi(.zig)` annotation (in the slot
|
||||
// before `extern`) followed by the library handle, on a function declaration. The
|
||||
// AST must carry the binding: `abi == .zig`, `extern_export == .extern_`, and the
|
||||
// library handle in `extern_lib`. No semantics yet — this is the first testable
|
||||
// sub-step of Phase 1 (parse only).
|
||||
test "parser: abi(.zig) extern <lib> binding parses on a fn decl" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const alloc = arena.allocator();
|
||||
|
||||
const src =
|
||||
\\compiler :: #library "compiler";
|
||||
\\text_of :: (id: StringId) -> string abi(.zig) extern compiler;
|
||||
\\intern :: (s: string) -> StringId abi(.zig) extern compiler;
|
||||
\\
|
||||
;
|
||||
var parser = Parser.init(alloc, src);
|
||||
const root = try parser.parse();
|
||||
|
||||
try std.testing.expect(root.data == .root);
|
||||
const decls = root.data.root.decls;
|
||||
try std.testing.expectEqual(@as(usize, 3), decls.len);
|
||||
|
||||
// The `#library` decl still parses to a `library_decl` node carrying the name.
|
||||
try std.testing.expect(decls[0].data == .library_decl);
|
||||
try std.testing.expectEqualStrings("compiler", decls[0].data.library_decl.name);
|
||||
try std.testing.expectEqualStrings("compiler", decls[0].data.library_decl.lib_name);
|
||||
|
||||
// The two `abi(.zig) extern compiler` fns: `.fn_decl` with the binding fields set.
|
||||
for ([_][]const u8{ "text_of", "intern" }) |bn| {
|
||||
var found: ?*const Node = null;
|
||||
for (decls) |d| {
|
||||
if (d.data.declName()) |n| {
|
||||
if (std.mem.eql(u8, n, bn)) found = d;
|
||||
}
|
||||
}
|
||||
const d = found orelse return error.MissingDecl;
|
||||
try std.testing.expect(d.data == .fn_decl);
|
||||
const fd = d.data.fn_decl;
|
||||
try std.testing.expectEqual(ast.ABI.zig, fd.abi);
|
||||
try std.testing.expectEqual(ast.ExternExportModifier.extern_, fd.extern_export);
|
||||
try std.testing.expect(fd.extern_lib != null);
|
||||
try std.testing.expectEqualStrings("compiler", fd.extern_lib.?);
|
||||
// Bodyless extern import: synthesized empty block, no `#builtin`/`#compiler`.
|
||||
try std.testing.expect(fd.body.data == .block);
|
||||
}
|
||||
}
|
||||
|
||||
// Lock: a bare `extern` (no abi annotation) leaves `abi == .default` — the
|
||||
// unannotated case is unchanged by the new `abi(...)` slot.
|
||||
test "parser: bare extern leaves abi == .default" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const alloc = arena.allocator();
|
||||
|
||||
const src =
|
||||
\\puts :: (s: *u8) -> i32 extern;
|
||||
\\
|
||||
;
|
||||
var parser = Parser.init(alloc, src);
|
||||
const root = try parser.parse();
|
||||
const decls = root.data.root.decls;
|
||||
try std.testing.expectEqual(@as(usize, 1), decls.len);
|
||||
try std.testing.expect(decls[0].data == .fn_decl);
|
||||
const fd = decls[0].data.fn_decl;
|
||||
try std.testing.expectEqual(ast.ExternExportModifier.extern_, fd.extern_export);
|
||||
try std.testing.expectEqual(ast.ABI.default, fd.abi);
|
||||
}
|
||||
|
||||
// Lock: `abi(.c)` parses standalone (no extern/export) in the postfix slot — the
|
||||
// migrated spelling of the old `callconv(.c)` on an ordinary function pointer /
|
||||
// fn decl. And `abi(.pure)` parses (naked-asm ABI).
|
||||
test "parser: abi(.c) and abi(.pure) parse standalone" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const alloc = arena.allocator();
|
||||
|
||||
const src =
|
||||
\\cb :: () -> i64 abi(.c) { 0; }
|
||||
\\nk :: () -> i64 abi(.pure) { 0; }
|
||||
\\
|
||||
;
|
||||
var parser = Parser.init(alloc, src);
|
||||
const root = try parser.parse();
|
||||
const decls = root.data.root.decls;
|
||||
try std.testing.expectEqual(@as(usize, 2), decls.len);
|
||||
try std.testing.expect(decls[0].data == .fn_decl);
|
||||
try std.testing.expectEqual(ast.ABI.c, decls[0].data.fn_decl.abi);
|
||||
try std.testing.expectEqual(ast.ExternExportModifier.none, decls[0].data.fn_decl.extern_export);
|
||||
try std.testing.expect(decls[1].data == .fn_decl);
|
||||
try std.testing.expectEqual(ast.ABI.pure, decls[1].data.fn_decl.abi);
|
||||
}
|
||||
|
||||
// Lock: the `compiler`-library binding PARSES on a STRUCT decl — `Name :: struct
|
||||
// abi(.zig) extern <lib> { … }`. The AST struct_decl must carry `abi == .zig` and
|
||||
// the library handle in `extern_lib`, with the field list intact. No semantics
|
||||
// yet (parse-only) — this is the second testable sub-step of Phase 1.
|
||||
test "parser: abi(.zig) extern <lib> binding parses on a struct decl" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const alloc = arena.allocator();
|
||||
|
||||
const src =
|
||||
\\compiler :: #library "compiler";
|
||||
\\Field :: struct abi(.zig) extern compiler { name: StringId; ty: Type; }
|
||||
\\
|
||||
;
|
||||
var parser = Parser.init(alloc, src);
|
||||
const root = try parser.parse();
|
||||
const decls = root.data.root.decls;
|
||||
try std.testing.expectEqual(@as(usize, 2), decls.len);
|
||||
|
||||
try std.testing.expect(decls[1].data == .struct_decl);
|
||||
const sd = decls[1].data.struct_decl;
|
||||
try std.testing.expectEqual(ast.ABI.zig, sd.abi);
|
||||
try std.testing.expect(sd.extern_lib != null);
|
||||
try std.testing.expectEqualStrings("compiler", sd.extern_lib.?);
|
||||
// Field list survives the binding annotation.
|
||||
try std.testing.expectEqual(@as(usize, 2), sd.field_names.len);
|
||||
try std.testing.expectEqualStrings("name", sd.field_names[0]);
|
||||
try std.testing.expectEqualStrings("ty", sd.field_names[1]);
|
||||
}
|
||||
|
||||
// Lock: an ordinary struct (no binding) leaves `abi == .default` / `extern_lib ==
|
||||
// null` — the new annotation slot doesn't perturb the common case.
|
||||
test "parser: plain struct leaves abi == .default, extern_lib == null" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const alloc = arena.allocator();
|
||||
|
||||
const src =
|
||||
\\Point :: struct { x: i64; y: i64; }
|
||||
\\
|
||||
;
|
||||
var parser = Parser.init(alloc, src);
|
||||
const root = try parser.parse();
|
||||
const decls = root.data.root.decls;
|
||||
try std.testing.expectEqual(@as(usize, 1), decls.len);
|
||||
try std.testing.expect(decls[0].data == .struct_decl);
|
||||
const sd = decls[0].data.struct_decl;
|
||||
try std.testing.expectEqual(ast.ABI.default, sd.abi);
|
||||
try std.testing.expect(sd.extern_lib == null);
|
||||
}
|
||||
|
||||
@@ -598,12 +598,12 @@ pub const Parser = struct {
|
||||
// '->' present: function type
|
||||
self.advance(); // skip '->'
|
||||
const return_type = try self.parseTypeExpr();
|
||||
const call_conv = try self.parseOptionalCallConv();
|
||||
const abi = try self.parseOptionalAbi();
|
||||
return try self.createNode(start, .{ .function_type_expr = .{
|
||||
.param_types = try param_types.toOwnedSlice(self.allocator),
|
||||
.param_names = if (has_names) try param_names.toOwnedSlice(self.allocator) else null,
|
||||
.return_type = return_type,
|
||||
.call_conv = call_conv,
|
||||
.abi = abi,
|
||||
} });
|
||||
}
|
||||
// No '->': tuple type (even for single element). Keep field names
|
||||
@@ -959,6 +959,18 @@ pub const Parser = struct {
|
||||
self.advance();
|
||||
}
|
||||
|
||||
// Optional welded-binding annotation: `struct abi(.zig) extern <lib> { … }`.
|
||||
// `abi(...)` (the ABI/layout selector) sits before the `extern` linkage
|
||||
// keyword, mirroring the fn-decl slot order; the library handle follows.
|
||||
// Parse-only for now — no layout/registry semantics yet.
|
||||
const struct_abi = try self.parseOptionalAbi();
|
||||
const struct_extern = self.parseOptionalExternExport();
|
||||
var struct_extern_lib: ?[]const u8 = null;
|
||||
if (struct_extern != .none and self.current.tag == .identifier) {
|
||||
struct_extern_lib = self.tokenSlice(self.current);
|
||||
self.advance();
|
||||
}
|
||||
|
||||
// Optional type params: struct($N: u32, $T: Type) { ... }
|
||||
var type_params = std.ArrayList(ast.StructTypeParam).empty;
|
||||
if (self.current.tag == .l_paren) {
|
||||
@@ -1146,6 +1158,8 @@ pub const Parser = struct {
|
||||
.using_entries = try using_entries.toOwnedSlice(self.allocator),
|
||||
.methods = try methods.toOwnedSlice(self.allocator),
|
||||
.constants = try constants.toOwnedSlice(self.allocator),
|
||||
.abi = struct_abi,
|
||||
.extern_lib = struct_extern_lib,
|
||||
.is_raw = name_is_raw,
|
||||
} });
|
||||
}
|
||||
@@ -1937,8 +1951,11 @@ pub const Parser = struct {
|
||||
return_type = try self.parseTypeExpr();
|
||||
}
|
||||
|
||||
// Optional calling convention: callconv(.c)
|
||||
const call_conv = try self.parseOptionalCallConv();
|
||||
// Optional ABI / calling-convention annotation: `abi(.c)` / `abi(.zig)` /
|
||||
// `abi(.pure)`. Sits in the postfix slot BEFORE the `extern`/`export`
|
||||
// linkage keyword (it is part of the function declaration). `abi(.zig)`
|
||||
// marks a binding to the comptime `compiler` library.
|
||||
const abi = try self.parseOptionalAbi();
|
||||
|
||||
// Optional postfix linkage modifier: `extern` (import) / `export` (define).
|
||||
const extern_export = self.parseOptionalExternExport();
|
||||
@@ -2018,7 +2035,7 @@ pub const Parser = struct {
|
||||
.body = body,
|
||||
.type_params = type_params,
|
||||
.is_arrow = is_arrow,
|
||||
.call_conv = call_conv,
|
||||
.abi = abi,
|
||||
.extern_export = extern_export,
|
||||
.extern_lib = extern_lib,
|
||||
.extern_name = extern_name,
|
||||
@@ -3688,8 +3705,8 @@ pub const Parser = struct {
|
||||
return_type = try self.parseTypeExpr();
|
||||
}
|
||||
|
||||
// Optional calling convention: callconv(.c)
|
||||
const call_conv = try self.parseOptionalCallConv();
|
||||
// Optional ABI annotation: abi(.c) / abi(.zig) / abi(.pure)
|
||||
const abi = try self.parseOptionalAbi();
|
||||
|
||||
// A closure is its own function boundary: clear the cleanup-body flags
|
||||
// so control-flow exits inside the closure body (`return` from the
|
||||
@@ -3719,7 +3736,7 @@ pub const Parser = struct {
|
||||
.return_type = return_type,
|
||||
.body = body,
|
||||
.type_params = type_params,
|
||||
.call_conv = call_conv,
|
||||
.abi = abi,
|
||||
} });
|
||||
}
|
||||
|
||||
@@ -3745,8 +3762,8 @@ pub const Parser = struct {
|
||||
// builtin marker) is a function-type literal, not a function def.
|
||||
if (tag == .arrow) return self.hasFnBodyAfterArrow();
|
||||
// `kw_extern`/`kw_export`: a postfix linkage modifier (e.g. `f :: () extern;`
|
||||
// with no return type) marks a fn decl just like `callconv`.
|
||||
return tag == .l_brace or tag == .hash_builtin or tag == .hash_compiler or tag == .fat_arrow or tag == .kw_callconv or tag == .kw_extern or tag == .kw_export;
|
||||
// with no return type) marks a fn decl just like `abi(...)`.
|
||||
return tag == .l_brace or tag == .hash_builtin or tag == .hash_compiler or tag == .fat_arrow or tag == .kw_abi or tag == .kw_extern or tag == .kw_export;
|
||||
}
|
||||
|
||||
fn hasFnBodyAfterArrow(self: *Parser) bool {
|
||||
@@ -3773,9 +3790,9 @@ pub const Parser = struct {
|
||||
if (self.current.tag == .fat_arrow) return true;
|
||||
if (self.current.tag == .l_brace) return true;
|
||||
if (self.current.tag == .hash_builtin or self.current.tag == .hash_compiler) return true;
|
||||
if (self.current.tag == .kw_callconv) return true;
|
||||
if (self.current.tag == .kw_abi) return true;
|
||||
// Postfix linkage modifier after the return type: `-> R extern;` /
|
||||
// `-> R export { … }` (and `-> R callconv(.c) extern`). Marks a fn def.
|
||||
// `-> R export { … }` (and `-> R abi(.c) extern`). Marks a fn def.
|
||||
if (self.current.tag == .kw_extern or self.current.tag == .kw_export) return true;
|
||||
// Inside a `struct #compiler` block, a `(...) -> Ret;` ending
|
||||
// with `;` after the return type is a `#compiler` method
|
||||
@@ -3806,25 +3823,32 @@ pub const Parser = struct {
|
||||
return false;
|
||||
}
|
||||
|
||||
fn parseOptionalCallConv(self: *Parser) anyerror!ast.CallingConvention {
|
||||
if (self.current.tag != .kw_callconv) return .default;
|
||||
/// Optional ABI / calling-convention annotation `abi(.c)` / `abi(.zig)` /
|
||||
/// `abi(.pure)` in the postfix slot before `extern`/`export`. `.default` when
|
||||
/// absent. Subsumes the old `callconv(...)` spelling.
|
||||
fn parseOptionalAbi(self: *Parser) anyerror!ast.ABI {
|
||||
if (self.current.tag != .kw_abi) return .default;
|
||||
self.advance();
|
||||
try self.expect(.l_paren);
|
||||
try self.expect(.dot);
|
||||
if (self.current.tag != .identifier)
|
||||
return self.fail("expected calling convention name after '.'");
|
||||
const cc_name = self.tokenSlice(self.current);
|
||||
const cc: ast.CallingConvention = if (std.mem.eql(u8, cc_name, "c")) .c else return self.fail("unknown calling convention");
|
||||
return self.fail("expected ABI name ('.c', '.zig', or '.pure') after '.'");
|
||||
const abi_name = self.tokenSlice(self.current);
|
||||
const abi: ast.ABI = if (std.mem.eql(u8, abi_name, "c"))
|
||||
.c
|
||||
else if (std.mem.eql(u8, abi_name, "zig"))
|
||||
.zig
|
||||
else if (std.mem.eql(u8, abi_name, "pure"))
|
||||
.pure
|
||||
else
|
||||
return self.fail("unknown ABI (expected '.c', '.zig', or '.pure')");
|
||||
self.advance();
|
||||
try self.expect(.r_paren);
|
||||
return cc;
|
||||
return abi;
|
||||
}
|
||||
|
||||
/// Postfix linkage modifier in the slot after `callconv(...)`:
|
||||
/// Postfix linkage modifier in the slot after `abi(...)`:
|
||||
/// `extern` (import) or `export` (define + expose), or `.none` if neither.
|
||||
/// Mirrors `parseOptionalCallConv`. Bare-keyword today; the optional
|
||||
/// `"csym"` symbol-name override lands in Phase 1.2/2.2. Defined here in
|
||||
/// Phase 0.1 but NOT yet called from any decl path (wired in Phase 1.0).
|
||||
fn parseOptionalExternExport(self: *Parser) ast.ExternExportModifier {
|
||||
switch (self.current.tag) {
|
||||
.kw_extern => {
|
||||
|
||||
14
src/sema.zig
14
src/sema.zig
@@ -830,7 +830,7 @@ pub const Analyzer = struct {
|
||||
switch (node.data) {
|
||||
.fn_decl => |fd| {
|
||||
const saved_cc = self.in_c_conv;
|
||||
self.in_c_conv = fd.call_conv == .c;
|
||||
self.in_c_conv = fd.abi == .c;
|
||||
try self.pushScope();
|
||||
try self.analyzeParams(fd.params);
|
||||
try self.analyzeNode(fd.body);
|
||||
@@ -852,7 +852,7 @@ pub const Analyzer = struct {
|
||||
if (mnode.data == .fn_decl) {
|
||||
const m = mnode.data.fn_decl;
|
||||
const saved_cc = self.in_c_conv;
|
||||
self.in_c_conv = m.call_conv == .c;
|
||||
self.in_c_conv = m.abi == .c;
|
||||
try self.pushScope();
|
||||
try self.analyzeParams(m.params);
|
||||
try self.analyzeNode(m.body);
|
||||
@@ -979,7 +979,7 @@ pub const Analyzer = struct {
|
||||
try self.diagnostics.append(self.allocator, .{
|
||||
.level = .warn,
|
||||
.span = span,
|
||||
.message = "`context` is unavailable in a `callconv(.c)` function — the C ABI has no implicit context parameter; pass what you need explicitly",
|
||||
.message = "`context` is unavailable in an `abi(.c)` function — the C ABI has no implicit context parameter; pass what you need explicitly",
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -1032,7 +1032,7 @@ pub const Analyzer = struct {
|
||||
});
|
||||
}
|
||||
const saved_cc = self.in_c_conv;
|
||||
self.in_c_conv = fd.call_conv == .c;
|
||||
self.in_c_conv = fd.abi == .c;
|
||||
try self.pushScope();
|
||||
try self.analyzeParams(fd.params);
|
||||
try self.analyzeNode(fd.body);
|
||||
@@ -2366,7 +2366,7 @@ test "sema: member references record fields, methods, and enum variants" {
|
||||
try std.testing.expect(red_use);
|
||||
}
|
||||
|
||||
test "sema: context in a callconv(.c) function reports a specific diagnostic" {
|
||||
test "sema: context in an abi(.c) function reports a specific diagnostic" {
|
||||
const parser_mod = @import("parser.zig");
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
@@ -2374,7 +2374,7 @@ test "sema: context in a callconv(.c) function reports a specific diagnostic" {
|
||||
|
||||
const source =
|
||||
"Context :: struct { allocator: i64; data: i64; }" ++
|
||||
"cb :: () -> i64 callconv(.c) { context; 0; }" ++
|
||||
"cb :: () -> i64 abi(.c) { context; 0; }" ++
|
||||
"ok :: () -> i64 { context; 0; }";
|
||||
var parser = parser_mod.Parser.init(alloc, source);
|
||||
const root = try parser.parse();
|
||||
@@ -2385,7 +2385,7 @@ test "sema: context in a callconv(.c) function reports a specific diagnostic" {
|
||||
var c_conv_diag = false;
|
||||
var undefined_diag = false;
|
||||
for (res.diagnostics) |d| {
|
||||
if (std.mem.indexOf(u8, d.message, "callconv(.c)") != null) c_conv_diag = true;
|
||||
if (std.mem.indexOf(u8, d.message, "abi(.c)") != null) c_conv_diag = true;
|
||||
if (std.mem.indexOf(u8, d.message, "undefined") != null) undefined_diag = true;
|
||||
}
|
||||
try std.testing.expect(c_conv_diag); // `cb` accesses context under the C ABI
|
||||
|
||||
@@ -42,7 +42,7 @@ pub const Tag = enum {
|
||||
kw_impl, // impl
|
||||
kw_Self, // Self (in protocol declarations)
|
||||
kw_inline, // inline (compile-time if/for/while)
|
||||
kw_callconv, // callconv (calling convention annotation)
|
||||
kw_abi, // abi (ABI / calling-convention annotation: abi(.c)/abi(.zig)/abi(.pure))
|
||||
kw_extern, // extern (import: external linkage, C ABI, no body)
|
||||
kw_export, // export (define + expose: external linkage, C ABI)
|
||||
kw_asm, // asm (inline assembly expression / global asm decl)
|
||||
@@ -281,7 +281,7 @@ pub const keywords = std.StaticStringMap(Tag).initComptime(.{
|
||||
.{ "impl", .kw_impl },
|
||||
.{ "Self", .kw_Self },
|
||||
.{ "inline", .kw_inline },
|
||||
.{ "callconv", .kw_callconv },
|
||||
.{ "abi", .kw_abi },
|
||||
.{ "extern", .kw_extern },
|
||||
.{ "export", .kw_export },
|
||||
// `asm` is a real keyword; `volatile` / `clobbers` stay OUT of this table
|
||||
|
||||
Reference in New Issue
Block a user